The name of the username parameter is username. This is the default value of the username parameter when Spring Security is configured by using Java configuration

The name of the password parameter is password. This the default value value of the password parameter when Spring Security is configured by using Java configuration.

If a form login fails, the user is redirected to url ‘/login?error=bad_credentials’. This means that when the login page is requested and the value of the of error request parameter is ‘bad_credentials’, we must show an error message to the user.

Show an error message if log in fails. We can get the localized error message by using the message tag of the Spring tag library if the value of the request parameter called error is ‘bad_credentials’.

Implement the login form by following these steps:

Ensure that when the login form is submitted, a POST request is send to url ‘/login/authenticate’.

Add CSRF token to the request which is send when the login form is submitted. This is required because we enabled the CSRF protection of Spring Security in the first part of this tutorial.

We have now created the login page which fulfils our requirements. The relevant part of our login page looks as follows:

Our next step is to implement the registration function. Let’s get started.

Implementing the Registration Function

The registration function of our example application has two requirements:

It must be possible to create a “normal” user account.

It must be possible to create a user account by using social sign in.

Also, the application context configuration which we created in the first part of this tutorial specifies one requirement for the registration function:

The url of the registration page must be ‘/signup’. This is the default value of the sign up (also known as registration) page, and at the moment it is not possible to override this url if we configure the application context by using Java configuration. However, since the url ‘/signup’ looks a bit ugly, we will replace this url with the url ‘/user/register’.

Note: It is possible to override the default value of the sign up url if the application context is configured by using XML configuration files (look for the property called signUpUrl).

The user of our example application can end up to the registration page by using one of the following methods:

He clicks the social sign in button which starts the social sign in flow.

Because it is hard to get the general idea from such a shallow description, I have created a diagram which illustrates the steps a user has to follow before he ends up to the registration page of our example application. This diagram has two rules:

The grey colour represents actions which are the responsibility of our example application.

The blue colour represents actions which are the responsibility of the SaaS API provider.

This diagram looks as follows:

Let’s move on and start by creating a form object for the registration form.

Creating the Form Object

The form object is a data transfer object which contains the information entered to the registration form and specifies the validation constraints which are used to validate that information.

Before we implement the form object, let’s take a quick look at the validation constraints which we use to validate our form object. These constraints are described in following:

The @Email annotation ensures that the email address given by the user is well-formed.

The @NotEmpty annotation ensures that the value of the field cannot be empty or null.

The @Size annotation ensures that the length of the field value isn’t longer than the maximum length of the field.

Let’s move on and create the form object. We can do this by following these steps:

Create a class called RegistrationForm.

Add an email field to the class and specify its validation constraints by following these rules:

The email must be well-formed.

The email cannot be empty or null.

The maximum length of the email is 100 characters.

Add a firstName field to the class and specify its validation constraints by following these rules:

The first name cannot be empty or null.

The maximum length of the first name is 100 characters.

Add a lastName field to the class and specify its validation constraints by following these rules:

The last name cannot be empty or null.

The maximum length of the last name is 100 characters.

Add a password field to the class.

Add a passwordVerification field to the class.

Add a signInProvider field to the class. The type of this field is SocialMediaService.

Add a isNormalRegistration() method to created class. This method returns true if the value of the signInProvider field is null. If the value of that field is not null, this method returns false.

Add a isSocialSignIn() method to the created class. This method returns true if the value of the signInProvider field is not null. If the value of that field is null, this method returns false.

Creating the Constraint Annotations

When we create the constraint annotations, we have to always follow these common steps:

This section explains how you can create the required constraint annotations. However, you don’t have to create the CustomConstraint annotation. I use it only as example that demonstrates the required steps, and it is not used in the actual example application.

Create an annotation type. Let’s assume that the name of our annotation type is CommonConstraint.

Annotate the created annotation type with the @Target annotation and set its value to {ElementType.TYPE, ElementType.ANNOTATION_TYPE} (the Javadoc of the ElementType enum). This means that both classes and annotation types can be annotated with the @CommonConstraint annotation.

Annotate the created annotation type with the @Retention annotation and set its value to RetentionPolicy.RUNTIME. This means that the @CommonConstraint annotation is available at runtime and it can be read by using reflection.

Annotate the created annotation type with the @Constraint annotation and set the value of its validatedBy attribute. The value of this attribute specifies the class which validates the classes annotated with the @CommonConstraint annotation.

Annotate the class with the @Documented annotation. This means that the @CommonConstraint annotation is visible in the Javadoc documentation of all classes which are annotated with it.

Add a message attribute to the annotation type. The type of this attribute is String, and its default value is ‘CommonConstraint’.

Add a groups attribute to the annotation type. The type of this attribute is an array of type Class<?>, and its default value is empty array. This attribute allows the creation of validation groups.

Add a payload attribute to the annotation type. The type of this attribute is an array of type Class<? extends Payload>, and its default value is empty array. This attribute is not used by the Bean Validation API but clients of the API can assign custom PayLoad objects to the constraint.

Let’s move on and find out how we can create the @PasswordsNotEmpty and @PasswordNotEqual annotations.

First, we have to create the @PasswordsNotEmpty annotation. We can do this by following these steps:

Follow the common steps described earlier and make the following changes to the created annotation:

Rename the annotation type to PasswordsNotEmpty.

Set the value of the @Constraint annotation’s validatedBy attribute to PasswordsNotEmptyValidator.class.

Add a triggerFieldName attribute to the annotation type. The type of this attribute is String, and its default value is empty string. This attribute specifies the name of the field which triggers our custom constraint if its value is null.

Add a passwordFieldName attribute to the annotation type. The type of this attribute is String, and its default value is empty string. This attribute specifies the name of the field which contains the password of the user.

Add a passwordVerificationFieldName attribute to to the annotation type. The type of this attribute is String, and its default value is empty string. This attribute specifies the name of the field which contains the password verification of the user.

The source code of the @PasswordsNotEmpty annotation looks as follows:

Second, we have to create the @PasswordsNotEqual annotation. We can do this by following these steps:

Follow the common steps described earlier and make the following changes to the created annotation:

Rename the annotation type to PasswordsNotEqual.

Set the value of the @Constraint annotation’s validatedBy attribute to PasswordsNotEqualValidator.class.

Add a passwordFieldName attribute to the annotation type. The type of this attribute is String, and its default value is empty string. This attribute specifies the name of the field which contains the password of the user.

Add a passwordVerificationFieldName attribute to the annotation type. The type of this attribute is String, and its default value is empty string. This attribute specifies the name of the field which contains the password verification of the user.

The source code of the @PasswordsNotEqual annotation looks as follows:

We are now ready to implement our validator classes. Let’s see how that is done.

Creating the Validator Classes

First, we have to create the validator class which can validate classes annotated with the @PasswordsNotEmpty annotation. We can do this by following these steps:

Create a PasswordsNotEmptyValidator class and implement the ConstraintValidator interface. The ConstraintValidator interface defines two type parameters which are described in the following:

The first type parameter is the annotation type. Set the value of this type parameter to PasswordsNotEmpty.

The second type parameter is the type of element which can be validated by the validator. Set the value of this type parameter to Object (We could set this to RegistrationForm but using the type Object ensures that our validator is not restricted to this example application).

Add a private validationTriggerFieldName field to the created class and set its type to String.

Add a private passwordFieldName field to the created class and set its type to String.

Add a private passwordVerificationFieldName field to the created class and set its type to String.

Add a private isNullOrEmpty(String field) method to the created class. This method returns true if the String given as a method parameter is null or empty. Otherwise this method returns false.

Add a private passwordsAreValid(Object value, ConstraintValidatorContext context) method to the created class. This method returns a true if the password fields are valid and false otherwise. This method takes two method parameters which are described in the following:

Obtain the value of the password field by calling the getFieldValue() method of the ValidatorUtil class. Pass the validated object and the name of the password field as method parameters.

If the value of the password field is empty or null, add a validation error by calling the addValidationError() method of the ValidatorUtil class. Pass the name of the password field and the ConstraintValidatorContext object as method parameters.

Obtain the value of the passwordVerification field by calling the getFieldValue() method of the ValidatorUtil class. Pass the validated object and the name of the password verification field as method parameters.

If the value of the password verification field is empty or null, add a validation error by calling the addValidationError() method of the ValidatorUtil class. Pass the name of the password verification field and the ConstraintValidatorContext object as method parameters.

Add a try-catch structure to the method and catch all checked exceptions. If a checked exception is thrown, catch it and wrap it inside a RuntimeException. This is required because the isValid() method of the ConstraintValidator interface cannot throw checked exceptions Implement the try block by following these steps:

Get the value of the validation trigger field by calling the getFieldValue() method of the ValidatorUtil class. Pass the validated object and the name of the validation trigger field as method parameters.

If the value of the validation trigger field is null, call the passwordFieldsAreValid() method and pass the validated object and the ConstraintValidatorContext object as method parameters. Return the boolean value returned by this method.

If the value of the validation trigger field is not null, return true.

The source code of the PasswordsNotEmptyValidator class looks as follows:

Second, we have to create the validator class which validates classes annotated with the @PasswordsNotEqual annotation. We can do this by following these steps:

Create a PasswordsNotEqualValidator class and implement the ConstraintValidator interface. The ConstraintValidator interface defines two type parameters which are described in the following:

The first type parameter is the annotation type. Set the value of this type parameter to PasswordsNotEqual.

The second type parameter is the type of element which can be validated by the validator. Set the value of this type parameter to Object (We could set this to RegistrationForm but using the type Object ensures that our validator is not restricted to this example application).

Add a private passwordFieldName field to the created class and set its type to String.

Add a private passwordVerificationFieldName field to the created class and set its type to String.

Add the initialize(PasswordsNotEqual constraintAnnotation) method of the ConstraintValidator interface to the validator class and implement it by following these steps:

Set the value of the passwordFieldName field.

Set the value of the passwordVerificationFieldName field.

Add a private passwordsAreNotEqual(String password, String passwordVerification) method to the created class. If the password and password verification given as method parameters aren’t equal, this method returns true. Otherwise this method returns false.

Add the isValid(Object value, ConstraintValidatorContext context) method of the ConstraintValidator interface to the validator class and implement it by following these steps:

Disable the default error message by calling the disableDefaultConstraintViolation() method of the ConstraintValidatorContext interface.

Add a try-catch structure to the method and catch all checked exceptions. If a checked exception is thrown, catch it and wrap it inside a RuntimeException. This is required because the isValid() method of the ConstraintValidator interface cannot throw checked exceptions Implement the try block by following these steps:

Get the value of the password field by calling the getFieldValue() method of the ValidatorUtil class. Pass the validated object and the name of the password field as method parameters.

Get the value of the password verification field by calling the getFieldValue() method of the ValidatorUtil class. Pass the validated object and the name of the password verification field as method parameters.

Check if passwords aren’t equal by calling the passwordsAreNotEqual() method. Pass the password and password verification as method parameters.

If the password and password verification aren’t equal, add validation error to both password and password verification fields by calling the addValidationError() method of the ValidatorUtil class. Return false.

That is it. We have now implemented our custom validation constraints. Let’s find out how we can render the registration page.

Rendering the Registration Page

The requirements of our registration page are following:

The url of the registration page must be ‘/user/register’.

If the user is creating a “normal” user account, our application must render an empty registration form.

If the user is using social sign in, the information provided by the SaaS API provider must be used to pre-populate the form fields of the registration form.

Let’s start by finding out how we can redirect user to the registration page.

Redirecting User to the Registration Page

Before we can start implementing the controller method which renders the registration page, we have to implement a controller which redirects user to the correct url. The requirements of this controller are following:

It must process GET requests send to url ‘/signup’.

It must redirect requests to url ‘/user/register’.

If you are configuring the application context of your application by using XML configuration files, you can skip this step. This step is required only if you configure the application context of your application by using Java configuration. The reason for this is that at the moment you can configure the sign up url only if you are using XML configuration (Search for a property called signUpUrl).

We can implement this controller by following these steps:

Create a SignUpController class and annotate the class with the @Controller annotation.

Add a public redirectRequestToRegistrationPage() method to the created class. The return type of this method is String.

Implement the redirectRequestToRegistrationPage() method by following these steps:

Annotate the method with the @RequestMapping annotation and ensure that the method processes GET requests send to url ‘/signup’.

Let’s move on and find out how we can implement the controller method which renders the registration page.

Implementing the Controller Method

The controller method which renders the registration page has one important responsibility:

It creates the form object and pre-populates its fields. If the user is creating a “normal” user account, this controller method creates an empty form object. On the other hand, if the user is creating a user account by using social sign in, this controller method sets the field values of the form object by using the information provided by the used SaaS API provider.

We can implement the controller method which renders the registration page by following these steps:

Create the controller class and annotate it with the @Controller annotation.

Annotate the class with the @SessionAttributes annotation and set its value to ‘user’. We use this annotation to ensure that a model attribute called ‘user’ (our form object) is stored to the session.

Add a private createRegistrationDTO() method to the class. This method takes a Connection object as a method parameter and returns a RegistrationForm object. We can implement this method by following these steps:

Create a new RegistrationForm object.

If the Connection object given as a method parameter is not null, the user is creating a new user account by using social sign in. If this is the case, we have to

Get a UserProfile object by calling the fetchUserProfile() method of the Connection class. This object contains the user information returned by the SaaS API provider.

Set the email, first name, and the last name to the form object. We can the get this information by calling the methods of the UserProfile class.

Get a ConnectionKey object by calling the getKey() method of the Connection class. This object contains id of the used social sign in provider and a provider specific user id.

Set the sign in provider to the form object by following these steps:

Get the sign in provider by calling the getProviderId() method of the ConnectionKey class.

Transform the String returned by the getProviderId() method to uppercase.

Get the correct value of the SocialMediaService enum by calling its nameOf() method. Pass the sign in provider (in uppercase) as a method parameter (This means that the values of the SocialMediaService enum depends from the sign in provider ids).

Set the returned value to the form object.

Return the form object.

The controller method which renders the registration page is called showRegistrationForm(). Add this method to the controller class and implement it by following these steps:

Annotate the method with the @RequestMapping annotation and ensure that controller method processes GET requests send to url ‘/user/register’.

Add a WebRequest object as a method parameter. We use the WebRequest as a method parameter because it gives us an easy access to request metadata.

Get a Connection object by calling the static getConnection() method of the ProviderSignInUtils class. Pass the WebRequest object as a method parameter. This method returns null if the WebRequest object doesn’t contain SaaS API provider metadata (this means that user is creating a normal user account). If the metadata is found, this method creates a Connection object by using that information and returns the created object.

Get the form object by calling the private createRegistrationDTO() method. Pass the Connection object as a method parameter.

Set the form object to model as a model attribute called ‘user’.

Return the name of the registration form view (‘user/registrationForm’).

The relevant part of the RegistrationController class looks as follows:

Add the created FieldError object to the binding result by calling the AddError() method of the BindingResult class.

Add a private createUserAccount() method to the controller class. This method returns the created User object, and takes a RegistrationForm and BindingResult objects as method parameters. If the email address is found from the database, this method returns null. Implement this method by following these steps:

Add a try-catch structure to the method and catch DuplicateEmailException objects.

Implement the try block by calling the registerNewUserAccount() method of the UserService interface. Pass the RegistrationForm object as a method parameter. Return the information of the created user account.

Implement the catch block by calling the private addFieldError() method. Pass the required information as method parameters. This ensures that the user receives an error message which informs him that the email address entered to the registration form is found from the database. Return null.

Add a public registerUserAccount() method to the controller class and implement it by following these steps:

Annotate the method with the @RequestMapping annotation and ensure that the method processes POST request send to url ‘/user/register’.

Add a RegistrationForm object as a method parameter and annotate it with the following annotations:

Annotate the method parameter with the @Valid annotation. This ensures that the information of this object is validated before the controller method is called.

Annotate the method parameter with the @ModelAttribute annotation and set its value to ‘user’ (this is the name of the form object).

Add a BindingResult object as a method parameter.

Add a WebRequest object as a method parameter. This object is required because we need to access the metadata of the request after the a new user account has been created.

If the binding result has errors, return the name of the form view.

Call the private createUserAccount() method and pass the RegistrationForm and BindingResult objects as method parameters.

If the User object returned by the createUserAccount() method is null, it means that the email address was found from the database. Return the name of the form view.

Log the created user in by calling the static loginInUser() method of the SecurityUtil class. Pass the created User object as a method parameter.

Call the static handlePostSignUp() method of the ProviderSignInUtils class. Pass the email address of the created user and the WebRequest object as method parameters. If the user created user account by using social sign in, this method persists the connection to the UserConnection table. If the user created a normal user account, this method doesn’t do anything.

The SecurityUtil class has one static method called loginInUser(). This method takes the information of the created user as a method parameter, and logs the user in programmatically. We can implement this method by following these steps:

It is not a good idea to log in a user who has created a normal user account. Typically you want to send a confirmation email which is used to verify his email address. However, the example application works this way because it simplifies the registration process.

Let’s move on and find out how we can create the domain model of our example application.

Creating the Domain Model

The domain model of our application consists of two classes and two enums which are described in the following:

The BaseEntity class is a superclass of all entity classes of our application.

The User class is the only entity class of our application. It contains the information of a single user.

The Role enum specifies the user roles of our application.

The SocialMediaService enum specifies the SaaS API providers which are supported by our example application.

Our example application doesn’t really need a separate base class for entities because it has only one entity. However, I decided to add it anyway because this is often a good idea in real life applications.

Let’s move on and find out how we can create the domain model.

First, we have to create a BaseEntity class. It contains the fields which are shared by all entity classes and two callback methods which are used to store values to some of those fields. We can implement this class by following these steps:

Create an abstract BaseEntity class which has one type parameter called ID. This parameter is the type of the entity’s private key.

Annotate the class with the @MapperSuperclass annotation. This means that the mapping information of the BaseEntity class is applied to its subclasses.

Add a DateTime field called creationTime to the class and configure it by following these steps:

Annotate the field with the @Column annotation and configure the name of the database column. The value of the nullable attribute to false.

Annotate the field with the @Type annotation and set the value of the type attribute to ‘org.jadira.usertype.dateandtime.joda.PersistentDateTime’ (Javadoc here). This marks the field as a custom type and configures the type class which makes it possible to persist DateTime objects with Hibernate.

Add a DateTime field called modificationTime to the class and configure it by using these steps:

Annotate the field with the @Column annotation and set the name of the database column. Ensure that this column is not nullable.

Annotate the field with the @Type annotation and set the value of the type attribute to ‘org.jadira.usertype.dateandtime.joda.PersistentDateTime’ (check step 3 for more details about this).

Add a long field called version to the class and annotate the field with the @Version annotation. This enables optimistic locking and states the value of the version field serves as optimistic lock value.

Add an abstract getId() method to the class. This method returns the id of the actual entity.

Add a public prePersist() method to the class and annotate the method with the @PrePersist annotation. This method is called before the entity manager persists the object, and it sets the current time as the value of the creationTime and the modificationTime fields.

Add a public preUpdate() method to the class and annotate the method with the @PreUpdate annotation. This method is called before the database UPDATE operation is performed. The implementation of this method sets the current time as the value of the modificationTime field.

Annotate the created class with the @Table annotation and ensure that the user information is stored to a database table called ‘user_accounts’.

Add a private id field to the class and set its type to Long. Configure the field by following these steps:

Annotate the field with the @Id annotation. This annotation is used to specify the primary key of the entity.

Annotate the field with the @GeneratedValue annotation and set the value of the strategy attribute to GenerationType.AUTO. This means that the persistence provider will pick the appropriate key generation strategy for the used database.

Add a private email field to the class and set its type to String. Annotate the field with the @Column annotation and configure the field by following these rules:

The email address is stored to the ’email’ column of the ‘users’ table.

The maximum length of the email address is 100 characters.

The email address cannot be null.

The email address must be unique.

Add a private firstName field to the class and set its type to String. Annotate the field with the @Column annotation and configure the field by following these rules:

The first name is stored to the ‘first_name’ column of the ‘users’ table.

The maximum length of the first name is 100 characters.

The first name cannot be null.

Add a private lastName field to the class and set its to type to String. Annotate the field with the @Column annotation and and configure the field by following these rules:

The last name is stored to the ‘last_name’ column of the ‘users’ table.

The maximum length of the last name is 100 characters.

The last name cannot be null.

Add a private password field to the class and set its type to String. Annotate the field with the @Column annotation and configure the field by following these rules:

The password is stored to the ‘password’ column of the ‘users’ table.

The maximum length of the password is 255 characters.

Add a private role field to the class and set its type to Role. Annotate the field with the @Enumerated annotation and set its value to EnumType.STRING. This means the value of this field is persisted as enumerated type and that a String value is stored to the database. Annotate the field with the @Column annotation and configure the field by following these rules:

The role is stored to the ‘role’ column of the ‘users’ table.

The maximum length of the role is 20 characters.

The role cannot be null.

Add a private signInProvider field to the class and set its type to SocialMediaService. Annotate the field with the @Enumerated annotation and set its value to EnumType.STRING (check step 9 for more details about this). Annotate the field with the @Column annotation and configure the field by following these rules:

The sign in provider is stored to the ‘sign_in_provider’ field of the ‘users’ table.

The maximum length of the sign in provider is 20 characters.

Add a public static inner class called Builder to the User class. Implement this class by following these steps:

Add a User field to the class. This field holds a reference to the constructed User object.

Add a constructor to the class. This constructor creates a new User object and sets the role of the created user to Role.ROLE_USER.

Add methods used to set the field values of created User object to the builder class. Each method sets the value given as a method parameter to the correct field and returns a reference to User.Builder object.

Add a build() method to the builder class. This method returns the created User object.

Add a public static getBuilder() method to the User class. This method returns a new User.Builder object.

The Role is an enum which specifies the user roles of our application. Its source code looks as follows:

public enum Role {
ROLE_USER
}

The SocialMediaService is an enum which identifies the SaaS API provider which was used to authenticate the user. Its source code looks as follows:

public enum SocialMediaService {
FACEBOOK,
TWITTER
}

Next we will find out how we can implement the service class which creates new user accounts and persists them to the database.

Creating the Service Class

First, we have to create an interface which declares the method used to add new user accounts to the database. This method is described in the following:

The registerNewUserAccount() method takes a RegistrationForm object as method parameter and returns a User object. If the email address stored to the email field of the RegistrationForm object is found from the database, this method throws a DuplicateEmailException.

Add a constructor which takes PasswordEncoder and UserRepository objects as constructor arguments to the service class. Implement the constructor by following these steps:

Annotate the constructor with the @Autowired annotation. This ensures that the dependencies of this bean are injected by using constructor injection.

Set the values of passwordEncoder and repository fields.

Add a private emailExist() method to the service class. This method takes a email address as a method argument and returns a boolean. Implement this method by following these steps:

Get the user whose email address is equal to the email address given as a method parameter by calling the findByEmail() method of the UserRepository interface. Pass the email address as a method parameter.

If a user is found, return true.

If a user is not found, return false.

Add a private encodePassword() method to service class. This method takes a RegistrationForm object as a method parameter and returns the encoded password. Implement this method by following these steps:

Find out if the user is creating a normal user account. We can get this information by calling the isNormalRegistration() method of the RegistrationForm class. If this method returns true, obtain the encoded password by calling the encode() method of the PasswordEncoder class. Pass the cleartext password as a method parameter. Return the encoded password.

If the user is creating a user account by using social sign in, return null.

Add a registerNewUserAccount() method to the service class and implement it by following these steps:

Annotate the method with the @Transactional annotation. This means that the method is executed “inside” a read-write transaction.

Find out if the email address is found from the database. We can do this by calling the private emailExist() method. Pass the RegistrationForm object as a method parameter. If this method returns true, throw a new DuplicateEmailException.

Obtain the encoded password by calling the private encodePassword() method. Pass the RegistrationForm object as a method parameter.

Get the builder object by calling the getBuilder() method of the User class and set the following information to the created User object:

Email address

First name

Last name

Password

Find out if the user is creating a new user account by using social sign in. We can do this by calling the method of the egistrationForm class. If this method returns true, set the used social sign in provider by calling the signInProvider() method of the User.Builder class. Pass the used sign in provider as a method parameter.

Create the User object.

Persist the User object to the database by calling the save() method of the UserRepository interface. Pass the created User object as a method parameter.

We still have to create the Spring Data JPA repository for our example application. Let’s find out how we can do this.

Creating the Spring Data JPA Repository

Our last step is to create a Spring Data JPA repository which is used to

Persist new User objects to the database.

Find a User object from the database by using email address as a search criteria.

We can create a Spring Data JPA repository which fulfils these requirements by following these steps:

Create the repository interface and extend the JpaRepository interface. Give the type of the entity (User) and type of its private key (Long) as type parameters. This gives us access to the methods declared by the JpaRepository interface. One of those methods is the save() method which is used to persist User objects to the database.

Add a findByEmail() method to the created repository interface. This method takes an email address as a method parameter and returns a User object whose email is equal to the email address given as a method parameter. If no user is found, this method returns null.

I tried the example with Jetty and it worked flawlessly, if you can suggest me how to make it work with tomcat that would be awsome. I have been following your blogs since one year and you are splendid with spring.

Thanks for coming back and leaving this comment! It seems that the active Spring profile was not configured when Tomcat was started.

The reason why I specified the profile was that I don’t want to use Facebook and Twitter for authentication when I write integration tests for the web layer (this is discussed in the fourth part of the tutorial).

It is good to hear that you like my blog post. Unfortunately I haven’t been able to find the Javadoc of the SpringSocialConfigurer class (or any other documentation about it). Actually, I read its source code when I was trying to figure out what it does. Do you have some questions concerning that class?

As you probably already noticed, this example application configures the web application by using Java configuration. If you are using a Servlet 3.0 compliant container such as Tomcat 7, there is no need to create the web.xml
file.

If you don’t want to use the Java configuration, you have to create the web.xml file. Remember to

Remove the @Profile annotation from the SocialContext class. You don’t need it if you don’t want to write integration tests for the registration function.

You have to set the active Spring profile when the servlet container is started. If you use Tomcat 7, you can do this by adding this line: spring.profiles.active=dev to the conf/catalina.properties file.

Great! The only reason why I use Spring profile in this example is that I want to investigate how I could write integration tests to this application (and especially to the registration function). To be more specific, I want to write integration tests which are not using the actual Facebook or Twitter API. I can achieve this goal by using a different Spring Social configuration when I run my integration tests.

First, if a user has registered a user account by using a normal registration, his information is not found from the UserConnection table. That is why the registration form is rendered when this user attempts to sign in by using social sign in.

You could of course try to add custom behavior to the sign in flow and use the email address obtained from the SaaS API provider to identify the user. This brings us to the second problem.

Second, you don’t necessarily get the email address of the user from all providers.

You can get it from Facebook if your application has been granted the email permission. On the other hand, you cannot get private information such as email address from Twitter.

In other words, if your application has to support SaaS API provider which doesn’t return the email address of the user, there is no clean way to this.

I’m trying to login through facebook and twitter. Though following this I could connect to FB, I’m getting the following error while trying the same for Twitter. Can you help me with what might went wrong?

HTTP ERROR 500

Problem accessing /auth/twitter. Reason:

Server Error
Caused by:

org.springframework.web.client.HttpClientErrorException: 406 Not Acceptable
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:88)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:537)

According to this page, the API should return a more descriptive error message in the response body. Can you see anything interesting in the response body (you can see this by setting your log level to DEBUG)?

Unfortunately the original error message is so vague that it is hard to say what is going without seeing any details, but I assume that the request is somehow malformed or some required information is missing.

You could also ensure that the configuration of your Twitter application is correct. To be more specific, you have to:

Ensure that the callback url is correct.

Verify that you have selected the ‘Allow this application to be used to Sign in with Twitter’ checkbox

That is pretty much everything I can figure out at the moment. I can investigate this issue further if you can provide me more information about the problem.

I have had exactly the same problem. Solved it exactly by providing callback URL.

By the way. Thanks for the great tutorial!!! The Spring Social examples are too simple and are showing just how to get the data like feeds from Facebook. The user data are then saved globally. Your example showed me how I can write an auth mechanism for multiple users using social accounts!

Hi, Petri,
You do a great work .
I am a beginner to the Spring Social. I got problems after I download and build you project.
1. I can register a user account, and database has the information of the account. But it display ‘??’ when I use UTF-8 characters in the field of lastname/firstname. I am using MySQL 5.1.65 and I created the database with utf8 option.
2. I can NOT login to the system when I use the account I registered above. It just tell me: Login failed!

I assume that you used Spring Security 3.2.0.RELEASE instead of 3.2.0.RC1? It seems that the changes made between these two versions break the example application. I will update the example application (and blog post) by following your instructions.

Yes, I figured that out when I noticed that the name of the method which is used to register authentication manager was changed from registerAuthentication() to configure() in Spring Security 3.2.0.RELEASE.

Thanks for the great tutorial, I wonder how to fix the error as below? I already registered apps on Facebook & Twitter and I also created the socialprofile.properties file with necessary security credentials on those 2 social platforms. I run the app on my local machine & compiled it with Java 1.6.

Thanks

HTTP ERROR 500

Problem accessing /auth/twitter. Reason:

Server Error
Caused by:

org.springframework.web.client.HttpClientErrorException: 406 Not Acceptable
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:88)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:537)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:493)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:465)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:416)
at org.springframework.social.oauth1.OAuth1Template.exchangeForToken(OAuth1Template.java:187)
at org.springframework.social.oauth1.OAuth1Template.fetchRequestToken(OAuth1Template.java:115)
at org.springframework.social.security.provider.OAuth1AuthenticationService.getAuthToken(OAuth1AuthenticationService.java:91)
at org.springframework.social.security.SocialAuthenticationFilter.attemptAuthService(SocialAuthenticationFilter.java:228)
at org.springframework.social.security.SocialAuthenticationFilter.attemptAuthentication(SocialAuthenticationFilter.java:147)

Hi Petri
Excellent post !!!
I really appreciate all your posts. To the point, precise and very well explained.

I am trying to solve exactly same use case using Spring Oauth2 and Google as the Authentication provider.

I am unable to figure out how to get started with it.
What filters to add, how to customize the UserDetailsService, how to create the Oauth2Token, how to extract user details from the response from Google authentication server….

Hi mr.petri .
i have the problem with our application connects to google+ and sign in there and it will be redirected to out application. (in one sentence i want to login to my application by using sign in with google(or any social website(facebook) account if it is exit otherwise it must be registered and login and it will be redirected to our application).

i think so you are the expert in this type of applications creation.
so i hope you can do this.
help me
thanq

If you want that your application creates a user account if it is not already found from the database and the social sign in successful, you should follow these steps:

Create a controller method that extracts the user information from the Connection object and ensure that this controller method is invoked if the user account is found. If you are using XML configuration, you can configure the sign up url. Otherwise you have to configure your controller method to process GET requests send to url ‘/signup’.

After you have extracted the user information from the Connection object, you have to create a new user account and save it to the database.

After you have saved the created user account to the database, you have to persist the connection to the UserConnection database table. You can do this by using the ProviderSignInUtils class.

Create a new SocialUserDetails object and log the user in.

If you have any further questions about this, don’t hesitate to ask them.

I want to thank you for your hard work and very detailed posts. They have helped this 13 year old java veteran jump in and adopt spring as the framework of choice for my first startup.

I have followed this post and got everything working in tomcat. I made a few changes and additions. One of the changes I made was to add a remember-me process. I did this by adding the bean PersistentTokenBasedRememberMeServices using JdbcTokenRepositoryImpl and the UserDetailsService that we built in your post. Everything seams like it is working great. I login and check the remember-me checkbox and it puts an entry into the persistent_logins table. I log out and it removes the entry from the persistent_logins table. This is great….Except

When I stop my server and force a cookie login (autologin) I get logged in but when I logout and then try to now log back in with the remember-me option again I get a lock on the table. There are a few other use cases that cause the lock but all of them happen once an atuologin is done.

Thanks for your reply. I looked into the removal of the cookie and found that this is done by default in AbstractRememberMeServices.cancelCookie(). I added a breakpoint and it is hitting this code when I log out. I don’t believe this is an issue of the cookie not being cleared.

I did a little more research while I was trying to track down the exact use-case and I have narrowed it down to the JdbcTokenRepositoryImpl.removeUserTokens() method. This calls the SQL that removes the token from the persistent_logins table.

It appears that once I “use a cookie login” and try to logout the record is not deleted and the row is locked. I can try to edit the record using mysqlworkbench and it will not let me commit the change until I kill the server and release the record.

Steps:
1. Login and select ‘remember me’ – Verify the record in the persistent_logins table.
2. Restart server
3. Use cookie login – Verified by adding a breakpoint to RepositoryUserDetailsService.loadUserByUsername(String) and see that we log the user in.
4. Log out – This should delete the record from the persistent_logins table but it does not go away and there is a lock on that row/table.
5. Any other action on that table by code or using SQL fails to work until you kill your server and release the lock.

If I do not take the route of “Use cookie login” and login and logout the record deletes from the persistent_logins table and there are not table locks.

FYI, I am using the following method in the view for logout. I am sure there is a better way but that is what I am doing for now. I thought I would include in case this could be the issue.

Thank you for providing additional details about your problem. I will try to reproduce the problem next weekend and hopefully find a fix to it (I will also update the dependencies of the example application).

Again I thank you for even looking into this. I looked at your branch and compared it to the master and it does not look like much changed in order to add the remember me feature. I made sure that I was following your syntax exactly just to make sure I did not miss something. I also looked back at you previous commits on the master branch and I also updated the spring and httpclient versions.

The bad news is that I am still having the issue. I did notice that the issue does not happen right away like it did before using the use-case that I explained above. I can repeat it by following steps 1-4 but the error does not happen on the first time i login but if I logout and then try to login again it does happen.

Steps:
1. Login and select ‘remember me’ – Verify the record in the persistent_logins table.
2. Restart server
3. Use cookie login – Verified by adding a breakpoint to RepositoryUserDetailsService.loadUserByUsername(String) and see that we log the user in.
4. Log out – This now does delete the record from the database.
5. Log in – This adds a token back to the database.
6. Log out – This should delete the record and does not.
7. Log in – This causes the browser to spin and then ends with a database lock error.

Its is like the issue is still there but not as prevalent. I also want to note that if I never exercise a cookie login I can log out and then over and over with no issues.

I am going to table this issue for a week or so but I will build a new project taking away any intellectual property and see if I can reproduce it. If I can I will share that GIT project with you. I will let you know.

I took a few pointers from this tutorial. I have used most of the things ditto, but I have replaced JPA with JCR JackRabbit as I need to store the data in a filesystem (local) and not in a DB. Everything has been fine-tuned except the Social Context part, where you have used a dataSource in JdbcUsersConnectionRepository. I need to find an alternative to that approach as in my case data is stored in a local filesystem. Can you please help me with that?
Thanks in advance.

I’ve just clone your project from Github but i am getting the following error in eclipse :Plugin execution not covered by lifecycle configuration: org.jacoco:jacoco-maven-plugin:0.6.3.201306030806:prepare-agent (execution: pre-unit-test, phase: initialize). I don’t know what to do ?

If you cannot solve the problem by following the advice given in M2E wiki, you can always delete the JaCoCo Maven plugin. It should solve your problem, but if you do this, you cannot create test coverage reports.

I have never done this so I am not sure what is the best way to do this. The first thing that comes to my mind is to follow these steps:

Create a service method which saves a new user account to the database.

Modify the SignUpController class to extract the required information from a Connection object (You can get a reference to a Connection object by calling the static getConnection() method of the ProviderSignInUtils class).

Call the service method which you created in step 1.

Log the created user in (You can use the static logInUser() method of the SecurityUtil class for this purpose).

Persist the connection to the UserConnection database table by calling the static handlePostSignUp() method of the ProviderSignInUtils class.

Redirect the request to the preferred url.

One possible problem of this approach is that you cannot get the email address from all social sign in providers. In other words, you cannot use the email address as username if you have to support a social sign in provider which doesn’t return the email address of the user.

Congrats you made an awesome job, really cool! The apps architecture is very interesting, union of many designs patterns in one app.

Maybe you can help me with one question, I need to create a web directory free from SpringSecurity auth, I tried to modify the SecurityContext but no success, the files I need are in .html and maybe It’s not possible to work with sitemesh, or Spring MVC. Can you give me a light how I can do it?

I have poor experience with SpringMVC, and then if I choose JSF framework instead, do you think it’s possible integrate JSF works with SpringSecurity, SpringData and SpringSocials?

I am happy to hear that this blog post and the example application were useful to you.

Let’s assume that the directory which contains your HTML files is called foo and it is found from the web application root (src/main/webapp/foo). You can permit all requests to the files found from this directory by using modifying the configure(HttpSecurity http) method of the SecurityContext class.

You can should modify this method by replacing the original authorization configuration with this one:

Remember that these matchers are processed in the same order than they are declared. That is why you need configure the urls which are not protected before configuring the matcher which protects the remaining urls. If you do this in the “wrong” order, the matcher ‘/**’ matches with all urls of your application, and only users who have the role ‘ROLE_USER’ can access it.

Unfortunately I haven’t used JSF so I cannot answer to your second question. However, I managed to find a few tutorials / so questions about this:

Thks Petri, with your help I can do what I need. My problem was in the order of matches.

About JSF, I did a integration of JSF and SpringSecurity a 3 years ago when SpringSecurity was in v2 and the configuration was in XML format. In the current times with SpringSecurity in v3 and anotations I don’t have any idea if this works like in the past. Mainly because I think Spring team don’t have interest in facilitate the life of a concurrent project JSF+ejb. Both are good, JSF have many nice features, but I think some important concepts like Dependency Injection was implemented in Spring first.

It’s time to make a decision and I’m entering in world of Spring, I’ll choose it for believe in his potential and many required framework like SpringSecurtiy, SpringSocial are essentials for my Project and will work better together with less adaptations. I’ll choose it, despite I have little knowledge in SpringMVC, almost zero… your article is helping me make this decison, thks a lot very clear article. Sorry about my English mistake, it’s not my native language.

It is good to hear that you were able to solve your problem. If you have very little experience from Spring MVC, you might want to check out Spring Boot. It takes an opinionated view of building Spring powered applications and you can avoid a lot of configuration if you are happy with the defaults.

By the way, don’t worry about your English. I think that it is just fine. :)

I’m doing some customizations in the user profile, I appreciate if you can check if I’m making the correct lesson.

I created an edit page where the user can update your informations. The way I’m doing it is creating an “User Profile” link pointing to the RegistrationController with the id of the user. Then I created a new interface and implemented it (findUserById(Long id)), and then when the user fill the .jsp page and submit through POST method the another controller method are invoked, received the form data and process it, In the controller I call a service to merge the information of user profile in the database.

Sounds good. I would probably create a new UserAccountController class and put the new controller methods to that class. The reason for this is that these are two separate functions (registration and update your information), and I prefer to keep their code separated. But other that, it seems that you have found the “right” way to do this.

In the jsp pages how I can discover all information we can get with the the tag .username, etc… Where it’s mapped? The property “principal.id” solve my problem, but maybe is interesting use this taglib in another pages that don’t needed to be edited to reduce app overhead.

Yes your explanation is very clear… After read your blog and anothers articles including JPA Data I conclude you are a high level development in Java and Spring. The best I can found in the web :P

I’m starting now in this frameworks, but how I had some experience with EJB3 and JSF I’m going good with Spring. Just one thing about another frameworks I used… JSF handle with AJAX and there is great features, another framework I recommend for view tier is DWR for AJAX too!… very interesting what they can do, very exiting, The DWR integration is very easy too, no obstacles with anothers frameworks.

But I’m really good impressioned with your Spring articles and your apps architectures! I’ll follow your recommendation in the another answer about UserController. Thks for the really good job Petri, long life for you!!!

Again, thank you so much for your kind words. I really appreciate them!

I think that one of the most important thing to remember is that you can learn new things every time you use new technologies. That is why think that everyone should try new things once in a while. I am sure that using Spring will teach you new skills which you can use if / when you decide to use Java EE in a new project.

What’s the best way to get the UserConnection.imageUrl attribute from database after authentication process. After create a new social user or authenticate an existent social user the RegistrationController persists the connection to the UserConnection table.

My intension is display the user profile image in some view area after social user are logged in webapp. I saw you done alguns JUnit tests doing it, but it’s seems to be a little complex.

I found a way to do it, off corse it isn’t the best, but the time is short and I needed to do it the fast way possible. This solution make easy to get any field from UserConnection table.

Basic steps
1. A new UserConnection Model was created, with all the attributes of the table.
2. A new service interface UserAccountServiceInterface was created with this signature public String getImageProfile(Integer id);

5. My new UserAccountController just calI the @Autowired service of the interface UserAccountServiceInterface:
String imageProfile = userAccountService.getImageProfile(id);
Then set it in the form, finaly the image profile is showed in the web interface. If there isn’t profile imagem (UserRegistration case) the service will return a blank string and the view tier can use an appropriate imagem showin a X or something else.

it is good to hear that you were able to solve your problem. I am sorry that I couldn’t answer to your question sooner but I was a bit busy. Have you considered adding a profileImageUrl field to the ExampleUserDetails class?

This way you could get the profile image information in the loadUserByUsername() method of the RepositoryUserDetailsService class, and you could access it by using the authentication tag.

Hi Petri,
please help me…
when I connect with Facebook, i see a registration page with name, surname and email (and all ok!). But when I click on “register” I get an 500 error and a redirect on my error page.
I’m very stuck!

Now I’ve another question…. this is the flow:
1) go to login page and click on “sign in with Facebook”
2) Facebook screen appear and I insert my email and pass
3) redirect to registration page and I insert my email again
4) User is registered correctly in database

but if i close my browser and come back in login page is impossible to log in with Facebook. The registration screen appears again…. why?

It seems that one possible reason for this is that the connection isn’t found from the UserConnection table. If this happens, the application assumes that user in question isn’t registered yet (and renders the registration form).

You can verify if this is the case by following these steps:

Put a break point to the last line of the findUserIdsWithConnection() method of the JdbcUsersConnectionRepository class.

You can find the JdbcUsersConnectionRepository class from the SocialContext class. The JdbcUsersConnectionRepository class is the class which is used to add new rows to the UserConnection table and find information from it.

The registerUserAccount() method of the RegistrationController class calls the handlePostSignUp() method of the ProviderSignInUtils class. This method inserts a new row to the UserConnection table.

I have setup my security and social very similarly to this tutorial and your previous one, however in the JSP the code wrapped in “” is being hidden for all users. When debugging I am finding that there is no securityContext for anonymous users. I have verified that my “httpSecurity” configuration is identical to yours. The only notable difference between my config and yours is that I am using “@EnableWebMvcSecurity” where as you are using “@EnableWebSecurity”. Can you point me in the right direction as to what may be causing the problem?

But I still have a question: when I sign in using facebook, I got redirected to my homepage with “#_=_” append to the URL (a facebook thing, no big deal). But what is bothering me is that I don’t want to go on the homepage after a successful connection but I want to display the dashboard. Is there a way to configure that?

I have the default-target-url attribute (for the normal login form) but there is no link with Spring social…

And I am using Spring security. After some investigations, the default URL is set from org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler using org.springframework.security.web.DefaultRedirectStrategy used someway by the new filter “socialAuthenticationFilter”. I cannot figure out how to override the default URL only for this filter.

By the way, I read the source code of the SocialAuthenticationFilter class, and noticed that you might want to set the value of the alwaysUsePostLoginUrl property to true. Otherwise the user might be redirected to another page if it is found from the request cache.

First, thanks a lot for this article. It was the best tutorial in using spring social!

I have successfully setup spring-social with spring security in my local but when I tried to deploy it on a tomcat running behind an nginx server, then my callback url is not working as it is using the tomcat’s internal domain name.

I tried to set applicationUrl on the ConnectController but it seems that it is not using the value. here’s how I did it.

It seems that Wordpress ate your XML configuration. Anyway, are you using the same Facebook or Twitter application for local development and your Tomcat server? If so, this might be the root cause of your problem.

The Facebook application has two settings which might cause problems if you use the same application:

The App Domains setting configures the domain name of your application.

The Server Url configures the url address of the website which uses Facebook login.

You should verify that the values of these settings are pointing to your Tomcat server.

On the other hand, if you use the same Twitter application for local development and Tomcat server, you will probably encounter this issue because Twitter allows only one callback URL per application.

I have typically created one Facebook and Twitter application per environment (local dev, test, and production) and I haven’t faced this problem yet. Although I have to admit that I haven’t used Spring Social in a production application yet (I have used only Spring Social 1.0).

I’m not sure where you’re getting your information, but
great topic. I needs to spend some time learning much more or understanding more.
Thanks for great information I was looking for this information for my mission.

I have one thing still not understand. It’s about the bean ‘connectionFactoryLocator’, I cannot find its declaration in your config but I see you config other bean reference to it. Below is your config that has reference to ‘connectionFactoryLocator’ bean:

The ConnectionFactoryLocator bean is provided automatically by Spring Social.

For example, if you annotate a configuration class with the @EnableSocial annotation, Spring Social will load beans configured in the SocialConfiguration class (this class configures the ConnectionFactoryLocator bean).

I haven’t paid a lot of attention to the XML configuration so unfortunately I am not sure which XML element enables the same behavior. :(

Where is the source of “CommonConstraintValidator” in “CommonConstraint”. I am getting error “For non-composed constraints a validator implementation must be specified using @Constraint#validatedBy()”.

I use the @CommonConstraint annotation as an example that explains the steps required to create new constraint annotations. In other words, you don’t have create this annotation. Do you think that this should be mentioned in the blog post?

Thanks Petri for quick reply, I am following this post from a week and trying to integrate piece by piece, I have used your code as it is, and i am not sure how to fix this issue. I thought you have explained every piece in so detail, so i was following things blindly, it would be great if you can help in this.

You have mentioned every possible detail, if you could provide some details on this also, i am sure it would help other followers as well.

I am trying to use successHandler and failureHandler with SpringSocialConfigurer together but as I understand SpringSocialConfigurer() is overriding my special success handler. So default successHandler is invoked after auhtentication completed. How can I solve this problem, how can I use them tohether?

If you configure the authentication success or failure handlers to by using a FormLoginConfigurer object, these handlers are called only when a form login is successful or it fails.

At the moment the SpringSocialConfigurer class provides very limited configuration options. You can only set post login url and post failure url.

If you need to use a sophisticated authentication success handler and authentication failure handler when the user of your application is using social sign in, you have to “modify” the SpringSocialConfigurer class to support custom authentication success handler and authentication failure handler. You can do this by following these steps:

copy-paste the source code of the SpringSocialConfigurer into a new class and add the setter methods that used to set the authentication success and failure handlers.

Modify the configure() method of your new class so that it sets the authentication success and failure handlers to the SocialAuthenticationFilter by using the setAuthenticationSuccessHandler() and setAuthenticationFailureHandler() methods.

Use your copy of the SpringSocialConfigurer class when you configure Spring Security.

Hello Petri!
Thanks for this great tutorial!
I have two questions:
1) In your answer about configuring authorized requests two different routs regarding redirects from spring social plugins: /signup and /signin. But in application exists only mapping to /signup. But I implement /signin mapping in mu application and I get strange requests to this route with empty connection info. What for this route? Should I implement it or not?
2) How I can implement saving of existing authorizations for keep users alive after redeploy?
Thanks!

I think that I simply forgot to remove the ‘/signIn/**’ ant pattern from the security configuration. I removed it from my local copy of the example application and everything was working as expected. In other words, you should remove it from your configuration as well.

Thank you for pointing this out. I will fix this tomorrow and update this blog post.

I’m trying to load this in Tomcat 7, and after removing the glassfish servlet dependency, ExampleApplicationConfig won’t compile unless I comment out the glassfish ServletRegistration.Dynamic stuff. After commenting out the first rootContext block and uncommenting the second, I’m able to compile and deploy to Tomcat, but the regular home page won’t show. This is my complete onStartup:

This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.

By the way, if you plan to use XML configuration instead of Java configuration, you should also remove the Spring profile configuration from the application context configuration file that configures Spring Social.

Ah yes. Its groupId was ‘org.glassfish’ so that was the confusion, although of course I replaced it with another servlet dependency – forgot to mention that. Anyway, I eventually got it working just fine using the java config. The XML config is what I want to use though, and it keeps throwing:

No bean named 'usersConnectionRepository' is defined

I have added ‘spring.profiles.active=dev’ to catalina.properties. @Profile was already missing from SocialContext.

After that, I tried it two ways. First, I followed the instructions in ExampleApplicationConfig, commenting and uncommenting. I left all the Filter definitions in place there. Got the above error. Here’s the java for review:

public void onStartup(ServletContext servletContext) throws ServletException {
//If you want to use the XML configuration, comment the following two lines out.
//AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
//rootContext.register(ExampleApplicationContext.class);

//If you want to use the XML configuration, uncomment the following lines.
XmlWebApplicationContext rootContext = new XmlWebApplicationContext();
rootContext.setConfigLocation("classpath:exampleApplicationContext.xml");

I want show on all pages user’s name from facebook (after he is authorized), now I saved it to database after signup, but if he change it in facebook it will not be changed on my site, what is the best way to do it? The only way is fetch user profile on login and get from there username?

My first thought was that you could do this by creating a custom AuthenticationSuccessHandler. I tried this out and noticed that it isn’t so simple.

First, you have to create your own copies of the SpringSocialConfigurer and SocialAuthenticationFilter classes (otherwise you cannot set the used AuthenticationSuccessHandler).

Second, you have to extract the Connection object from the request. The problem is that the ProviderSignInUtils class doesn’t find the Connection object if it is used in a AuthenticationSuccessHandler. I assume that the reason is that the request that is passed to the AuthenticationSuccessHandler object is the request that was created when a user clicks a social sign in link. This request is not the same request that is send to the social sign in provider, and that is why the Connection object is not found.

In other words, I don’t know how you can do this. I will add your question to my Trello board and take a closer look at it when I have got time to do it.

When I am trying to integrate your code with my project I am getting the below error.

java.lang.NoSuchMethodError: org.springframework.expression.spel.SpelParserConfiguration.(Lorg/springframework/expression/spel/SpelCompilerMode;Ljava/lang/ClassLoader;)V
at org.springframework.context.expression.StandardBeanExpressionResolver.(StandardBeanExpressionResolver.java:98)
at org.springframework.context.support.AbstractApplicationContext.prepareBeanFactory(AbstractApplicationContext.java:553)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:455)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)

I was able to reproduce this problem with Glassfish 4.1. When I clicked the ‘Create user account’ link, the server rendered an error page with response status 404. I found the following lines from the log file of my application:

I have been trying to find the solution to this problem, but I haven’t found anything useful. I found this StackOverflow question but it didn’t solve this problem. I think that I am not able to solve this problem. :(

Also, because it is “impossible” to find new tutorials that describe how I can deploy a Spring web application in Glassfish, I assume that no one is using Glassfish for running Spring web applications. That is why I recommend that you should replace Glassfish with Tomcat.

Hello Petri. I’m a korean developer. I read your posts such as JPA and this article..
I’m very appreciate of your posts.

Because It’s hard to find good and practical Spring tutorials in korea blogs.
So.. Can I translate your post into Korean post and share with develop community member?
If you say yes. I will be very pleased.
Of course I’ll mark origin link and your name in my translated post.

And yes, you can translate my articles into Korean as long as you as link back to the original article.

By the way, I am going to update my Spring Data JPA tutorial because the old one is becoming obsolete. You might want to wait for the new tutorial before you translate it because it will be a lot better.

One feedback I would like to provide & I hope you don’t take it wrong. Would it be possible for you to share an implementation which relies on just JPA and not Spring Data? Many users don’t use Spring Data (including me) and may find the implementation helpful.

I am using JPA/Hibernate and not using Spring Data for accessing my database. I want to know which steps I should perform for persisting a social user in UserConnection table in RegistrationController.registerUserAccount().

Your example makes a call to ProviderSignInUtils.handlePostSignUp(registered.getEmail(), request) which in turn relies on Spring Data for persisting information about new user. How should I do this in my code? Which interfaces/functions I have to implement so that they get called automatically by the framework for inserting / searching contacts? I don’t see you anywhere inserting records in userconnection table but in my case, I think I need to create DAO/Service layers for the same.

How should I do this in my code? Which interfaces/functions I have to implement so that they get called automatically by the framework for inserting / searching contacts? I don’t see you anywhere inserting records in userconnection table but in my case, I think I need to create DAO/Service layers for the same.

If you only want to insert data to the UserConnection table, you don’t have to make any changes to the application because this information is persisted by using JDBC.

Thanks for confirming this Petri. Looks like I was doing mistake elsewhere and the code was all set. I just rebuilt everything and called the postSignup() and realized that connection information was getting stored properly.
I am able to log in through FB, LI and Twitter and I thank you for all your support.

You are welcome. It is good to hear that you were able to solve your problem.

Also, thank you for coming back and asking these questions. Every question helps me to get a better understanding of the problems that other developers face, and this helps me to do a better job when I update this tutorial.

I assume that the your log has a stacktrace and / or other errors before the error message which states that the application context couldn’t be started because of previous errors. Could you add those errors here as well?

Also, it seems that you are loading two “root context” configuration files: WEB-INF/spring/root-context.xml and /WEB-INF/spring/exampleApplicationContext.xml. Do these files contain configuration that can cause a conflict?

I have to admit that I am not sure what is wrong. Your web.xml file looks correct to me, and it should work if you are using the correct version of Sitemesh and your sitemesh3.xml file has no errors in it.

Have you tried lowering the log level to DEBUG? If so, did you find anything useful from the log file?

Hi Petri. I have a question to the tutorial. After signing up with Facebook the info I get is only the first and last name. There is no e-mail address. I researched a bit and it turned out that to get it I have to specify it in so called scope as ’email’. Unfortunately all the examples are with a form with POST parameter while in your tutorial there is a simple link ‘auth/facebook’. How can I set the scope in your example?

By the way, if you transform the ‘Sign in with Facebook’ link into a form, you should be able to add the hidden email parameter to the request. I haven’t tried this myself, but it would be interesting to know if it is possible to pass the scope as a hidden POST parameter.

Hi Petri. Great tutorial. I want to extend this model further and include email verification of new accounts. After the user creates the account, the account would be in an unverified state until the user clicks on a verification link in his email. If the user attempts to login with an unverified state, the user would be redirected to a page with the text indicating the account is unverified as of yet. Any attempt to go to any url on the website after login would always redirect the user. I know how to send email with verification token and how to process if the user comes in with the link, but how do I intercept url if user does not come in with the link? Do I have to setup my own filter and check if user is unverified?

I would probably create a servlet filter that would check if the logged in user hasn’t verified his/her user account. The reason for this is that I don’t want to “pollute” the authorization logic with code that is required only to fulfill this special requirement.

If you figure out another solution to this problem, I would love to hear it!

First of all, a big thanks for such a detailed tutorial. I appreicate all your hardwork.
Now, I am running a spring MVC ( broadleaf ecom) and trying to setup the social login / Register.
I have gone through your post and did not understand one thing.
What exactly is happening on the register page ?

How Do, I show or the customer specify that they want to use the social profile details for login.
I mean, its Just Login, there is NOTHING like social registration. I mean, I can have my registration form, but I cannot have something like “Register using facebook” . Its just that on the sign-in page, I can show “Login with Facebook” and once the user logs in , I may get the profile details and create a user in my DB. But when the user returns, he will again use “Login with Facebook” ?

First of all, a big thanks for such a detailed tutorial. I appreicate all your hardwork.

Thank you for your kind words. I really appreciate them!

How Do, I show or the customer specify that they want to use the social profile details for login.

The user can select this by either entering his/her email and password to the login form or clicking the appropriate social sign in link. The UI is probably a bit rough but it is good enough for this purpose (this is just a tutorial).

I mean, its Just Login, there is NOTHING like social registration. I mean, I can have my registration form, but I cannot have something like “Register using facebook” . Its just that on the sign-in page, I can show “Login with Facebook” and once the user logs in , I may get the profile details and create a user in my DB. But when the user returns, he will again use “Login with Facebook” ?

Actually this is the way social sign in works in most of the websites that use form login and social sign in (and require additional information from the user). You can of course skip the registration form if you don’t need to ask additional information from the user. I wanted to add this step here because it might be required if you need to get the email address of the user (all social sign in providers don’t return the email address).

I think that you can probably to make this more obvious by adding a help text which explains how the login/registration flow works.

hi, Petri
I tried to go around with this great tutorial, but I find it very customized and full of unnecessary stuff,
hmm and some methods are deprecated.
it would be awesome if you could summarize this tutorial for those who already have their app running and just want to plug it into spring social to sign in a user
still this is a great work and helped me very much, though I couldn’t get my app running yet
regards,
Ali

Hi Petrik,
Problems again.
When I update the Spring Security to 4.0.1 the project gave me an error : “java.lang.NoSuchMethodError: org.springframework.social.security.SocialAuthenticationFilter.getFilterProcessesUrl()Ljava/lang/String;” when I try to run it on Tomcat.
I have no idea with this problem.

Its nice post. I have one doubt that how application authenticate through facebook credential and redirect to ” /signup” . Basically i don’t understand that where we have configure about application redirect to “/signup” page” after successfully sign in via Facebook , please explain in detail.

I am sorry that it took me couple of days to answer to your question. Anyway, Spring Social redirects user to the url ‘/signup’ when it doesn’t found a user account from the database. If you want to configure this url, you have two options:

If you configure your application by using Java configuration, you cannot change this url without creating a custom SpringSocialConfigurer class. That is why I implemented a simple controller method that redirects user from the url ‘/signup’ to the url ‘/user/register’.

If you use XML configuration, you have to set value of the postLoginUrl property of the SocialAuthenticationFilter class. If you want that the application always uses this url, you have to set the value of the alwaysUsePostLoginUrl property to true

Hi Petri,
the ProviderSignInUtils.getConnection(request) method which is used in Registration controller is now deprecated. instead it is suggested to use a getConnectionFromSession method. can you please help in how to use this method as it requires a number of parameters which are not available.

You can simply pass a WebRequest object as a method parameter to the controller method which invokes the getConnectionFromSession() method of the ProviderSignInUtils class. Because the WebRequest interface extends the RequestAttributes interface, you can then pass it as a method parameter to the getConnectionFromSession() method.

I have some issues with this configuration:
First I use the config for version 1.1.0 of spring social, and the result of the connection variable on ‘@RequestMapping(value = “/user/register”, method = RequestMethod.GET)’ is null.

Then I tried to use the second config for version 1.1.2. The problem here is that there is the following exception on Glassfish:

If you use the second configuration, you need to use Spring Social 1.1.2 or newer. The exception is thrown because the constructor in question was not found for some reason. For example, you might have multiple Spring Social jars in the classpath and a class loader might load the wrong one. Unfortunately it’s kind of impossible to say what the exact problem is without debugging the problematic application.

I fixed the error and the app runs normally, but the connection variable is still null.
Do you think is it an issue of the first request the app does on the granted service?
If it is that how I could control what the app is asking to do the granted service?

Hello Petri , thank you so much for the great article. I have been facing the issue from couple of days, couldnt find what going wrong. I am trying to login with github authentication and when i comes back from github app, the connection is always null. I dont have any object user.
private UserService service;

Hi Petri,
i am using your application with xml configurations and have defined a web.xml with following servlet mapping.

dispatcher
*.hop

However my spring security functions are not working properly, as in the code inside
and
are not getting executed, however if i comment the spring security tags things are working fine. can you please specify the issue, as i am not able to find one.

Hi Petri,
yes the related link is exactly the same problem i am facing. i am using a web.xml with just one servlet mapping. i have not mapped anything for spring security filter chain mapping or site mesh filter. However the springSecurityXml and sitemesh xml is the same as your code on git.
Can you please help me with the configuration for web.xml.
currently i am not able to use any spring security tags on jsp pages (i have included security libs on jsp pages).
My web.xml just contains the following mapping.

Hi Petri,
I tried the app with your git code. it works fine. there is just one small thing. i am not able to load any css for the whole app, all the designs are blank and i am not able to see any design on the app. i think there is something wrong with sitemesh configuration. here is my filter mapping of web.xml

I cannot find any errors from your Sitemesh configuration. I noticed that you configure your web application by using web.xml (the example application uses Java config). Did you make any other changes to it?

Also, which HTTP status code is returned when the browser requests the CSS file from the server?

Firstly thanks for the great document and example codes. What I want to ask is what if I want to allow my users connect their account with their social media accounts? For example, I have an account, and I want to connect it my facebook AND twitter accounts. What is the tips you can give me for this purpose?

Do you mean that the users should be able to log in by using both Facebook and Twitter accounts after they have connected their account with their social media accounts?

If so, the user has to be logged in when she/he tries to connect her/his user account with her/his social media accounts because you need to store the correct userId to the UserConnection table. This is required even if you use email address as username because all social media services don’t return the email address of the user.

Of course, the user can still create a user account by using a social sign in provider, but she/he cannot connect it with another social media account unless she/he is logged in.

Hi Petri,
Thank you for your interest to write a good article .
It is being applied to the project . Hit the obstacles I wanted one thing but the question to you.
Create and apply during the spring social as xml. But the problem is not the action.
As you talk to the older 1.1.2 version you should have set the providerSignInUtils as bean.
Is this job include non- xml ?

I have to admit that I am not entirely sure what you are trying to do. If you want to configure the page in which the user is redirected after he/she has signed in, you have to use one of the following (or both) methods:

If you want to configure the page in which the user redirected after social sign in, you have to set the value of the postLoginUrl property.

Unfortunately, I have to admit that I don’t know how you can do this (without sacrificing the safety of your existing users). I did a fast Google search, but I couldn’t find anything useful. It is surprising since this sounds like a pretty common use case.

Petri,
I would like to get some Facebook data other than the name, email. I want to get birthday, gender, and others. I put these params on the .jsp login facebook button to require the permission, and I’m trying to get these on createRegistrationDTO() using the object Connection, but I have no idea how can I call FacebookTemplate or othe object that retrieve these fields.. Can you suggest something?
Thanks. Nice tutorial.

Spring.io has a tutorial titled: Accessing Facebook Data that describes how you can read user’s profile from Facebook (it has an example application on Github as well). Does it help you to solve your problem?

Petri,
I want to redirect the user after the login to internal page, like a “dashboard”. Actually is redirecting to front page.
I tried to set ‘authentication-success-handler-ref=”myAuthenticationSuccessHandler”‘ on but didn’t work. Didn’t enter on the method “onAuthenticationSuccess”. My bean refers to a ‘SimpleUrlAuthenticationSuccessHandler’ implementation. I was following this tutorial to do this (http://www.baeldung.com/spring_redirect_after_login). I tried too to put ‘default-target-url=”/dashboard”‘ on but didn’t work.
I just want redirect my user after pass through UserDetailsService or SocialDetailsService to my internal page. Can you suggest something?
Thanks

Hi
I am worndking on a web application, new in spring and want to login using facebook or twitter account using spring.

I have gone through your project in detail and want to learn things using it. Problem is when I run unit test I get error. Please let me know if you can figure it out.

Exception in thread “main” java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:386)
FATAL ERROR in native method: processing of -javaagent failed
at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401)
Caused by: java.lang.RuntimeException: Class java/util/UUID could not be instrumented.
at

Given URL is not permitted by the Application configuration: One or more of the given URLs is not permitted by the App’s settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App’s domains.

Hi Petri,
i am beginner for spring social . I have been observed the total example,every thing i am able to understand.But as part of socialUsersDetailService class why userDetailsService is taken as reference.Can we please elaborate the relation between those two classes .

The example application has a social sign in and a normal form login. This means that:

When the user signs in by using social sign in, Spring Social loads the logged in user by using the class which implements the SocialUserDetailsService interface.

When the user signs in by using social sign in, Spring Security loads the logged in user by using the class which implements the UserDetailsService interface.

Also, the application uses the email address of the user as a userId which is saved to the UserConnection table. Because the email address is also the username of the user, the SimpleSocialUserDetailsService class can load it by using the functionality that is provided by the RepositoryUserDetailsService class.

Hi Petri,
Thank you every much for your answer.
Here i am unable to understand functionality of SignInUtils class .
I have return providerSignInUtils.doPostSignUp(—,—–); to save details into user connection table .
But the user details are not storing into user connection table.
Thanks In advance.

I created an dashboard to the user interact with the backend and the data of the system. I want to show some info for the user in the mainpage, and in your configuration page he can change some things of your account (by example: last name, date of birth, etc..).

The problem is that the findWebApplicationContext() method is not found from the SecurityWebApplicationContextUtils class. I assume that your classpath has jar files that belong to different Spring Security versions because that method is present in Spring Security 4.0.x. However, if you use Spring Security 3.2.x, that method is not found.

You can see this yourself when you compare the Javadocs of the SecurityWebApplicationContextUtils class:

I have not used Hibernate 5 yet, and I am not sure if this problem is related to it. However, you should remove the eclipselink and hibernate-annotations dependencies from your pom.xml. There are two reasons for this:

If you want to get user’s email address from Facebook, you need to configure your application to request the email permission. If I remember correctly, you have to configure the value of the scope property of your FacebookConnectionFactory object.

If you use Java configuration, you can set the correct scope by invoking the setScope() method of the OAuth2ConnectionFactory class (The FacebookConnectionFactory class extends this class). If you use my example application, you can find the relevant configuration from the SocialContext class.

Hi Petri ,
Thanks for great Tutorial.
I have been completed half of the application.
Your application simply says user contain only one role but from side user contains list of roles.
How can i handle this task.Thanks in advance.

I would store the user roles in a separate table and add these roles into my user entity by using the @ElementCollection and @CollectionTable annotations. If you have any additional questions, don’t hesitate to ask them!

Hi Petri,
I have completed total application.
i had a doubt regarding welcome page.I kept index page as welcome page.
when OAuth dance is completed,the request is coming back to index page.
i have written home controller to map “/” request .
please help me how to write login as welcome page in xml configuration.

Hi Petri
i have followed all your instructions still i am getting this error
400. That’s an error.
Error: invalid_request
Missing required parameter: scope
Could you please suggest me any other approach.

Small improvement from previous exception
I refer from stack over flow “the request should be post in case google sign in”.
here the error page after login into google is
400. That’s an error.
Error: redirect_uri_mismatch
I have hope your experience will able to solve this exception.

I apologize for many comments.
Google redirect the user to /signin after accepting on the google page where you allow my application access to your google+ account. /signin is a 404.
i hope your answer could helpful for me.

There is no need to apologize. The problem is that I don’t know the answers to your questions because I have never used Spring Social Google. :( I tried to find some answers from Google as well, but I couldn’t find anything useful.

Hi Petri
I am Happy to say that i have completed the google sign in.
Here /sign is given as default authentication failure in social authentication filter.
I enabled few services in google developer console.
Then remaining as usual.
Thanks for helping to make this task complete.

That is weird. I tested the link with FF, Chrome, and Opera. It seems that for some reason Chrome doesn’t open the correct comment :( You can find it by clicking the link and searching for the text: ‘wojciech’ (the alias of the person who asked the original question).

Petri, What do you think about code the front-end using Thymeleaf instead of JSP?
I’m thinking to migrate my projects to use thymeleaf..I read in the web a lot of stuffs saying that is much better to work with Thymeleaf, and JSP is too old.

I have never tried Thymeleaf because nowadays I write mostly single page web applications that have a REST backend. That being said, I have noticed that Thymeleaf is becoming quite popular, and that is why I would evaluate it if I would have to write a “normal” web application.

By the way, I don’t think that you should give much value to opinions you read from the internet because you cannot know the motives of these persons. In other words, if something is working for you, you should use it.

Cool. thanks for the answer. What frameworks are you using to write the single page applications nowadays? Are you combining the SPA with the Spring backend?
I’m thinking to buy a administrator dashboard template and use Angular to work on the front-end. But I’m studying the ways. Maybe I can work with SPA instead of this..

I noticed from the StackOverflow question that you mentioned that you are redirected to the url: ‘/signin’ after you have signed in with Google+. The thing is that another reader had the same problem, and he was able to fix it by enabling some services on Google developer console (unfortunately he didn’t mention which services he enabled).

In other words, I suggest that you enable all services on Google developer console and see if the Google+ sign in flow is working correctly. If it does work, you can disable these services one by one and figure out what services have to be enabled.

Thank you Petri, I’ve read a lot spring social and spring security articles and yours is the best. I am trying to create the same application with spring boot, but without hibernate, just Jdbc, since I’ve learnt hibernate yet.

But there are a few problems which I still could not solve after reading this tutorial and the previous one. Here is my source code https://github.com/maxiwu/SocialLogin
1. I look into your project, couldn’t find any controller that handle login POST, does this mean by configuring spring security correctly, it handles it for us? My application needs me to explicitly write method to handle login POST which I learn from some spring social example.
2. My project is not functioning properly, If I local in with a registered local user, it does render the /home, but the url is showing /login. and if I request for /home again, it bounces me back and render login page.
If I login with social user, I am trying facebook, it does redirect me to facebook login and after login, gives me 403 error.
I think this is caused by spring security not correctly configure, I just not yet figure out how.
3. The spring social sample use a Form POST with /signin/facebook, with a hidden field name ‘scope’ which define facebook scope, for example email,user_friends,user_posts,user_about_me.
But your sample is using hyperlink /auth/facebook without any scope. What is the difference between /signin/facebook and /auth/facebook? How do I defined scope with a hyperlink? Do I need to do so?

I look into your project, couldn’t find any controller that handle login POST, does this mean by configuring spring security correctly, it handles it for us? My application needs me to explicitly write method to handle login POST which I learn from some spring social example.

My project is not functioning properly, If I local in with a registered local user, it does render the /home, but the url is showing /login. and if I request for /home again, it bounces me back and render login page. If I login with social user, I am trying facebook, it does redirect me to facebook login and after login, gives me 403 error. I think this is caused by spring security not correctly configure, I just not yet figure out how.

When I wrote this blog post, the SocialAuthenticationFilter processed requests send to the url: /auth/provider_id, and there was no way to configure this url. It is possible that the default url has been changed after I published this blog post OR it is now possible to configure it.

How do I defined scope with a hyperlink? Do I need to do so?

If you want to specify a scope, you need to transform the hyperlink into a form.

Hi Petri, Your articles contain a lot of information, helps us understand more about how to use spring social and security. But I do not know liquibase, so I ran into a little problem. I am using mariadb instead of mysql, people say they are 100% compatible.

I followed the readme on github. When did table like user_accounts get created? I execute the command ‘mvn liquibase:update -P dev’, two tables created databasechangelog and databasechangeloglock. I guess they are for liquibase.
Then I execute ‘mvn jetty:run -P dev’, it gives me Missing table exception. So there is something wrong when I try to initialize database with liquibase?

I followed the readme on github. When did table like user_accounts get created?

My example projects creates them when you run the command mvn liquibase:update -P dev on command prompt. The Liquibase change log is found from the etc/db directory. However, nowadays I configure my Spring application to make the required changes to the database when the application is started. If you use Spring Boot, you should check out its reference documentation.

I execute the command ‘mvn liquibase:update -P dev’, two tables created databasechangelog and databasechangeloglock. I guess they are for liquibase.

You are correct. The databasechangelog table contains the Liquibase metadata that identifies the invoked change sets. The databasechangeloglock table is used to ensure that only one Liquibase instance can be running at one time.

Then I execute ‘mvn jetty:run -P dev’, it gives me Missing table exception. So there is something wrong when I try to initialize database with liquibase?

Yes, it seems so. However, it’s kind of impossible to say what it is because I cannot see the Liquibase output. Could you add the output to pastebin.com?

Hi Petri!
Thanks for the excellent tutorial: detailed and clear!
I just wanted to note that clearly Spring API have changed – weird, since the version I’m using is 1.1.4 (only build has changed, I didn’t expect modifications to the contract).
At any rate the static method ProviderSignInUtils.getConnection(Request) you mentioned isn’t available any longer.
For anyone else facing this change, here’s the official doc: http://docs.spring.io/spring-social/docs/current/reference/htmlsingle/#signing-up-after-a-failed-sign-in
Be aware that the method getConnection has been renamed in getConnectionFromSession

You are right! I cannot remember anymore why they made these changes, but I have a vague memory that it had got something to do with session management. Anyway, thank you for your comment. I am sure that it will be useful to people who run into this problem.

I wanted to check up and allow you to know how , a great
deal I treasured discovering your web blog today. I might consider it the honor to work at my workplace and be able to make real use of the tips contributed on your web-site
and also take part in visitors’ reviews like this.
Should a position regarding guest article writer become on offer at your end, make sure you let
me know.

this is a very informative blog, and I am able to at least start with spring social now.

I had setup this in an xml configuration, but as soon as I click on the facebbok button (/auth/facebook), it gives me a 404 error, I have spend a week no, but seems there is no way out to get rid of it. look like it is not finding the correct controller to handle /auth/facebbok request.

can you please advice what am I doing wrong, or which controller will handle this?

The url: ‘/auth/facebook’ is processed by the SocialAuthenticationFilter class. If you get 404 error when you try to access it, your configuration might not be correct (it’s hard to say for sure without seeing your code). You could check that you are using the configuration that is explained in this blog post.

First, I need to apologize that it took me so long to answer to your comment.

I took a look at your XML configuration and noticed you don’t configure the ConnectController bean. If you take a look at my Spring Social configuration, you should find that bean from the bottom of the XML file. You need to configure this bean because it creates connections to Social sign in providers and persists the connections by using the ConnectionRepository bean.

I have to admit that I don’t know if this solves your problem, but you might try it. Also, keep in mind that this tutorial is based on a very old version of Spring Social, and the newer versions might have some changes that are not compatible with my example. What Spring Social version are you using?

I cannot see this propert of ‘SocialAuthenticationServiceRegistry’ being set in you example.

As far as I know, you don’t need to set this property if you want to use the default behavior.

Thankyou for your response.
I was using 1.1.4 version, but then switched to versions used in your example and I could solve this issue. I could move forward but still seem to be stuck.
I have modified my security xml as follows :

Now my request goes to facebook, gives me a valid token, but i am getting error in
org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository, where ConnectionSignUp object is null. I am not sure where to configure this bean, or do I need to write an implementation for this.

What would you like to do when the social sign in provider redirects user back to your service? You mentioned that you want to handle to code that is returned by Facebook. What do you want to do with it?

The last time I checked, Spring Social didn’t have “any support” for Javascript web applications. If you want to use Spring Boot, you have to basically use the backend sign-in and sign-up flows. That being said, I was able to find this blog post that explains how you can integrate React with Spring Social (kind of). I hope that it helps you to solve your problem.