Do you want to be a better Java developer? If so, check out 10 Books Every Java Developer Should Read.

Adding Social Sign In to a Spring MVC Web Application: Registration and Login

Share
Socia media icons on a keyboard

The first part of this tutorial described how we can configure Spring Social 1.1.0 and Spring Security 3.2.0 but it left two very important questions unanswered.

These questions are:

  • How can a user create a new user account?
  • How can a user log in?

It is time to get our hands dirty and answer to these questions. The requirements of our example application are:

  • It must be possible to create a “traditional” user account. This means that the user is authenticated by using username and password.
  • It must be possible to create a user account by using a SaaS API provider such as Facebook or Twitter. In this case, the user is authenticated by the SaaS API provider.
  • It must be possible to log in by using username and password.
  • It must be possible to log in by using a SaaS API provider.

Let’s start fulfilling these requirements. The first thing that we have to do is to create a login page for our application.

Creating the Login Page

The login page of our application has three responsibilities which are described in the following:

  1. It must provide a way to log in by using username and password.
  2. It must have a link to the registration page. If a user wants to create “traditional” user account, he can do this by clicking this link.
  3. It must have the links which start the social sign in flow. These links can be used for two purposes:
    • If the user in question has a user account, he can log in by using a SaaS API provider.
    • If the user doesn’t have a user account, he can create one by using a SaaS API provider.

The application context configuration which we created in the first part of this tutorial specifies some requirements for our login page. These requirements are:

  1. If an anonymous user tries to access a protected page, he is redirected to url ‘/login’.
  2. When the login form of our application is submitted, our application must create a POST request to url ‘/login/authenticate’.
  3. We must include a CSRF token to the POST request which is created when our login form is submitted. The reason for this is that the CSRF protection of Spring Security 3.2.0 is enabled by default when we configure Spring Security by using Java configuration.
  4. 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
  5. 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.
  6. 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.
  7. The SocialAuthenticationFilter processes GET requests send to url ‘/auth/{provider}’. This means that
    • We can start the Facebook sign in flow by sending a GET request to url ‘/auth/facebook’.
    • We can start the Twitter sign in flow by sending a GET request to url ‘/auth/twitter’.

Let’s start by creating a controller which renders the login page.

Creating the Controller

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

  1. Create a LoginController class and annotate the created class with the @Controller annotation.
  2. Add a showLoginPage() method to the controller class. This method returns the name of the rendered view.
  3. Implement the showLoginPage() method by following these steps:
    1. Annotate the method with the @RequestMapping annotation and ensure that the showLoginPage() method processes GET requests send to url ‘/login’.
    2. Return the name of the login view (‘user/login’).

The source code of the LoginController class looks as follows:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String showLoginPage() {
        return "user/login";
    }
}

Our next step is to create the login page by using JSP. Let’s see how this is done.

Creating the JSP Page

We can create the login page by following these steps:

  1. Ensure that that the login form and social sign in buttons are shown only to anonymous users. We can do this by following these steps:
    1. Wrap the login form and social sign in buttons inside the authorize tag of the Spring Security tag library.
    2. Set the value of the access attribute to isAnonymous().
  2. 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’.
  3. Implement the login form by following these steps:
    1. Ensure that when the login form is submitted, a POST request is send to url ‘/login/authenticate’.
    2. 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.
    3. Add a username field to the login form.
    4. Add a password field to the login form.
    5. Add a submit button to the login form.
  4. Add ‘Create user account’ link below the login form. This link creates a GET request to url ‘/user/register’ (registration page).
  5. Add social sign buttons to the login page by following these steps:
    1. Add Facebook sign in button. This button must create a GET request to url ‘/auth/facebook’.
    2. Add Twitter sign in button. This button must create a GET request to url ‘/auth/twitter’.
  6. Ensure that a help message is shown if an authenticated user accesses the login page. We can do this by following these steps:
    1. Wrap the error message area inside the authorize tag of the Spring Security tag library.
    2. Set the value of the access attribute to isAuthenticated().
    3. Get the localized error message by using the message tag of the Spring tag library.

The source code of the login.jsp page looks as follows:

<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/social-buttons-3.css"/>
</head>
<body>
<div class="page-header">
    <h1><spring:message code="label.user.login.page.title"/></h1>
</div>
<!--
    If the user is anonymous (not logged in), show the login form
    and social sign in buttons.
-->
<sec:authorize access="isAnonymous()">
    <!-- Login form -->
    <div class="panel panel-default">
        <div class="panel-body">
            <h2><spring:message code="label.login.form.title"/></h2>
            <!--
                Error message is shown if login fails.
            -->
            <c:if test="${param.error eq 'bad_credentials'}">
                <div class="alert alert-danger alert-dismissable">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                    <spring:message code="text.login.page.login.failed.error"/>
                </div>
            </c:if>
            <!-- Specifies action and HTTP method -->
            <form action="/login/authenticate" method="POST" role="form">
                <!-- Add CSRF token -->
                <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
                <div class="row">
                    <div id="form-group-email" class="form-group col-lg-4">
                        <label class="control-label" for="user-email"><spring:message code="label.user.email"/>:</label>
                        <!-- Add username field to the login form -->
                        <input id="user-email" name="username" type="text" class="form-control"/>
                    </div>
                </div>

                <div class="row">
                    <div id="form-group-password" class="form-group col-lg-4">
                        <label class="control-label" for="user-password"><spring:message code="label.user.password"/>:</label>
                        <!-- Add password field to the login form -->
                        <input id="user-password" name="password" type="password" class="form-control"/>
                    </div>
                </div>
                <div class="row">
                    <div class="form-group col-lg-4">
                        <!-- Add submit button -->
                        <button type="submit" class="btn btn-default"><spring:message code="label.user.login.submit.button"/></button>
                    </div>
                </div>
            </form>
            <div class="row">
                <div class="form-group col-lg-4">
                    <!-- Add create user account link -->
                    <a href="/user/register"><spring:message code="label.navigation.registration.link"/></a>
                </div>
            </div>
        </div>
    </div>
    <!-- Social Sign In Buttons -->
    <div class="panel panel-default">
        <div class="panel-body">
            <h2><spring:message code="label.social.sign.in.title"/></h2>
            <div class="row social-button-row">
                <div class="col-lg-4">
                    <!-- Add Facebook sign in button -->
                    <a href="<c:url value="/auth/facebook"/>"><button class="btn btn-facebook"><i class="icon-facebook"></i> | <spring:message code="label.facebook.sign.in.button"/></button></a>
                </div>
            </div>
            <div class="row social-button-row">
                <div class="col-lg-4">
                    <!-- Add Twitter sign in Button -->
                    <a href="<c:url value="/auth/twitter"/>"><button class="btn btn-twitter"><i class="icon-twitter"></i> | <spring:message code="label.twitter.sign.in.button"/></button></a>
                </div>
            </div>
        </div>
    </div>
</sec:authorize>
<!--
    If the user is already authenticated, show a help message instead
    of the login form and social sign in buttons.
-->
<sec:authorize access="isAuthenticated()">
    <p><spring:message code="text.login.page.authenticated.user.help"/></p>
</sec:authorize>
</body>
</html>

Note: Our application uses Twitter Bootstrap 3. The social sign in buttons are created by using a Twitter Bootstrap plugin called Social Buttons for Twitter Bootstrap 3.

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

social-login-form

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:

  1. It must be possible to create a “normal” user account.
  2. 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:

  1. He clicks the ‘Create user account link. This link starts the “normal” registration process.
  2. 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:

  1. The grey colour represents actions which are the responsibility of our example application.
  2. The blue colour represents actions which are the responsibility of the SaaS API provider.

This diagram looks as follows:

registration

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:

  1. Create a class called RegistrationForm.
  2. Add an email field to the class and specify its validation constraints by following these rules:
    1. The email must be well-formed.
    2. The email cannot be empty or null.
    3. The maximum length of the email is 100 characters.
  3. Add a firstName field to the class and specify its validation constraints by following these rules:
    1. The first name cannot be empty or null.
    2. The maximum length of the first name is 100 characters.
  4. Add a lastName field to the class and specify its validation constraints by following these rules:
    1. The last name cannot be empty or null.
    2. The maximum length of the last name is 100 characters.
  5. Add a password field to the class.
  6. Add a passwordVerification field to the class.
  7. Add a signInProvider field to the class. The type of this field is SocialMediaService.
  8. 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.
  9. 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.

The source code of the RegistrationForm class looks as follows:

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

import javax.validation.constraints.Size;

@PasswordsNotEmpty(
        triggerFieldName = "signInProvider",
        passwordFieldName = "password",
        passwordVerificationFieldName = "passwordVerification"
)
@PasswordsNotEqual(
        passwordFieldName = "password",
        passwordVerificationFieldName = "passwordVerification"
)
public class RegistrationForm {

    @Email
    @NotEmpty
    @Size(max = 100)
    private String email;

    @NotEmpty
    @Size(max = 100)
    private String firstName;

    @NotEmpty
    @Size(max = 100)
    private String lastName;

    private String password;

    private String passwordVerification;

    private SocialMediaService signInProvider;

    //Constructor is omitted for the of clarity.
   
    public boolean isNormalRegistration() {
        return signInProvider == null;
    }

    public boolean isSocialSignIn() {
        return signInProvider != null;
    }
   
    //other methods are omitted for the sake of clarity.
}

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
}

Wait, didn’t we just forget something?

What on earth are those weird annotations such as @PasswordsNotEqual and @PasswordsNotEmpty?

Well, they are custom bean validation constraints. Let’s find out how we can create these constraints.

Creating the Custom Validation Constraints

We have to create two custom validation constraints for our example application. If the user is creating a “normal” user account, we have to ensure that:

  1. The password and passwordVerification fields of our form object cannot be empty or null.
  2. The password and passwordVerification fields are equal.

We can create custom validation constraints by following these steps:

  1. Create a constraint annotation.
  2. Implement a custom validator class which ensures that the constraint is not broken.

Note: The reference manual of Hibernate validator 4.2 has more information about creating custom validation constraints.

Let’s start by creating the constraint annotations.

Creating the Constraint Annotations

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

  1. Create an annotation type. Let’s assume that the name of our annotation type is CommonConstraint.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. Add a message attribute to the annotation type. The type of this attribute is String, and its default value is ‘CommonConstraint’.
  7. 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.
  8. 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.

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

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target( { TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = CommonConstraintValidator.class)
@Documented
public @interface CommonConstraint {

    String message() default “CommonConstraint”;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

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:

  1. Follow the common steps described earlier and make the following changes to the created annotation:
    1. Rename the annotation type to PasswordsNotEmpty.
    2. Set the value of the @Constraint annotation’s validatedBy attribute to PasswordsNotEmptyValidator.class.
  2. 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.
  3. 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.
  4. 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:

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target( { TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordsNotEmptyValidator.class)
@Documented
public @interface PasswordsNotEmpty {

    String message() default "PasswordsNotEmpty";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String triggerFieldName() default "";

    String passwordFieldName() default "";

    String passwordVerificationFieldName() default "";
}

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

  1. Follow the common steps described earlier and make the following changes to the created annotation:
    1. Rename the annotation type to PasswordsNotEqual.
    2. Set the value of the @Constraint annotation’s validatedBy attribute to PasswordsNotEqualValidator.class.
  2. 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.
  3. 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:

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target( { TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordsNotEqualValidator.class)
@Documented
public @interface PasswordsNotEqual {

    String message() default "PasswordsNotEqual";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String passwordFieldName() default "";

    String passwordVerificationFieldName() default "";
}

We have now created our constraint annotations. Let’s move on and take a look at a utility class which we use when we are implementing the validator classes for our custom constraint annotations.

Creating the Validation Utility Class

The validation utility class provides two static methods which are described in the following:

  • The first method is used to add validation errors to a field of the validated object.
  • The second method returns the value of the requested field.

We can implement this class by following these steps:

  1. Create a class called ValidatorUtil.
  2. Add a addValidationError() method to the ValidatorUtil class. This method takes two parameters which are described in the following:
    1. The first parameter is the name of the field.
    2. The second parameter is a ConstraintValidatorContext object.
  3. Implement the addValidationError() method by following these steps:
    1. Create a new constraint violation and ensure that the message specified by the constraint annotation is used as a prefix when the constraint violation message is build.
    2. Add the field to the constraint validation error.
    3. Create the constraint validation error.
  4. Add a getFieldValue() method to the ValidatorUtil class. This method returns the field value of the specified field and takes two parameters which are described in the following:
    1. The first parameter is the object which contains the requested field.
    2. The second parameter is the name of the requested field.
  5. Implement the getFieldValue() method by following these steps:
    1. Get a reference to the Field object which reflects the requested field.
    2. Ensure that we can access the value of the field even if the field is private.
    3. Return the field value.

The source code of the ValidatorUtil class looks as follows:

import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;

public class ValidatorUtil {

    public static void addValidationError(String field, ConstraintValidatorContext context) {
        context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                .addNode(field)
                .addConstraintViolation();
    }

    public static Object getFieldValue(Object object, String fieldName) throws NoSuchFieldException, IllegalAccessException {
        Field f = object.getClass().getDeclaredField(fieldName);
        f.setAccessible(true);
        return f.get(object);
    }
}

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:

  1. Create a PasswordsNotEmptyValidator class and implement the ConstraintValidator interface. The ConstraintValidator interface defines two type parameters which are described in the following:
    1. The first type parameter is the annotation type. Set the value of this type parameter to PasswordsNotEmpty.
    2. 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).
  2. Add a private validationTriggerFieldName field to the created class and set its type to String.
  3. Add a private passwordFieldName field to the created class and set its type to String.
  4. Add a private passwordVerificationFieldName field to the created class and set its type to String.
  5. Add the initialize(PasswordsNotEmpty constraintAnnotation) method of the ConstraintValidator interface to the validator class and implement it by following these steps:
    1. Set the value of the validationTriggerFieldName field.
    2. Set the value of the passwordFieldName field.
    3. Set the value of the passwordVerificationFieldName field.
  6. 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.
  7. 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:
    1. The first method parameter is the validated object.
    2. The second method parameter is a ConstraintValidatorContext object.
  8. Implement the passwordsAreValid() method by following these steps:
    1. 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.
    2. 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.
    3. 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.
    4. 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.
    5. If validation errors were found, return false. Otherwise return true.
  9. Add the isValid(Object value, ConstraintValidatorContext context) method of the ConstraintValidator interface to the validator class and implement it by following these steps:
    1. Disable the default error message by calling the disableDefaultConstraintViolation() method of the ConstraintValidatorContext interface.
    2. 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:
      1. 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.
      2. 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.
      3. If the value of the validation trigger field is not null, return true.

The source code of the PasswordsNotEmptyValidator class looks as follows:

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PasswordsNotEmptyValidator implements ConstraintValidator<PasswordsNotEmpty, Object> {

    private String validationTriggerFieldName;
    private String passwordFieldName;
    private String passwordVerificationFieldName;

    @Override
    public void initialize(PasswordsNotEmpty constraintAnnotation) {
        validationTriggerFieldName = constraintAnnotation.triggerFieldName();
        passwordFieldName = constraintAnnotation.passwordFieldName();
        passwordVerificationFieldName = constraintAnnotation.passwordVerificationFieldName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        context.disableDefaultConstraintViolation();
        try {
            Object validationTrigger = ValidatorUtil.getFieldValue(value, validationTriggerFieldName);
            if (validationTrigger == null) {
                return passwordFieldsAreValid(value, context);
            }
        }
        catch (Exception ex) {
            throw new RuntimeException("Exception occurred during validation", ex);
        }

        return true;
    }

    private boolean passwordFieldsAreValid(Object value, ConstraintValidatorContext context) throws NoSuchFieldException, IllegalAccessException {
        boolean passwordWordFieldsAreValid = true;

        String password = (String) ValidatorUtil.getFieldValue(value, passwordFieldName);
        if (isNullOrEmpty(password)) {
            ValidatorUtil.addValidationError(passwordFieldName, context);
            passwordWordFieldsAreValid = false;
        }

        String passwordVerification = (String) ValidatorUtil.getFieldValue(value, passwordVerificationFieldName);
        if (isNullOrEmpty(passwordVerification)) {
            ValidatorUtil.addValidationError(passwordVerificationFieldName, context);
            passwordWordFieldsAreValid = false;
        }

        return passwordWordFieldsAreValid;
    }

    private boolean isNullOrEmpty(String field) {
        return field == null || field.trim().isEmpty();
    }
}

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

  1. Create a PasswordsNotEqualValidator class and implement the ConstraintValidator interface. The ConstraintValidator interface defines two type parameters which are described in the following:
    1. The first type parameter is the annotation type. Set the value of this type parameter to PasswordsNotEqual.
    2. 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).
  2. Add a private passwordFieldName field to the created class and set its type to String.
  3. Add a private passwordVerificationFieldName field to the created class and set its type to String.
  4. Add the initialize(PasswordsNotEqual constraintAnnotation) method of the ConstraintValidator interface to the validator class and implement it by following these steps:
    1. Set the value of the passwordFieldName field.
    2. Set the value of the passwordVerificationFieldName field.
  5. 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.
  6. Add the isValid(Object value, ConstraintValidatorContext context) method of the ConstraintValidator interface to the validator class and implement it by following these steps:
    1. Disable the default error message by calling the disableDefaultConstraintViolation() method of the ConstraintValidatorContext interface.
    2. 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:
      1. 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.
      2. 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.
      3. Check if passwords aren’t equal by calling the passwordsAreNotEqual() method. Pass the password and password verification as method parameters.
      4. 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.
      5. If password and password verification were are, return true.

The source code of the PasswordsNotEqualValidator looks as follows:

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PasswordsNotEqualValidator implements ConstraintValidator<PasswordsNotEqual, Object> {

    private String passwordFieldName;

    private String passwordVerificationFieldName;

    @Override
    public void initialize(PasswordsNotEqual constraintAnnotation) {
        this.passwordFieldName = constraintAnnotation.passwordFieldName();
        this.passwordVerificationFieldName = constraintAnnotation.passwordVerificationFieldName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        context.disableDefaultConstraintViolation();
        try {
            String password = (String) ValidatorUtil.getFieldValue(value, passwordFieldName);
            String passwordVerification = (String) ValidatorUtil.getFieldValue(value, passwordVerificationFieldName);

            if (passwordsAreNotEqual(password, passwordVerification)) {
                ValidatorUtil.addValidationError(passwordFieldName, context);
                ValidatorUtil.addValidationError(passwordVerificationFieldName, context);

                return false;
            }
        }
        catch (Exception ex) {
            throw new RuntimeException("Exception occurred during validation", ex);
        }

        return true;
    }

    private boolean passwordsAreNotEqual(String password, String passwordVerification) {
        return !(password == null ? passwordVerification == null : password.equals(passwordVerification));
    }
}

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:

  1. The url of the registration page must be ‘/user/register’.
  2. If the user is creating a “normal” user account, our application must render an empty registration form.
  3. 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’.

Note: 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:

  1. Create a SignUpController class and annotate the class with the @Controller annotation.
  2. Add a public redirectRequestToRegistrationPage() method to the created class. The return type of this method is String.
  3. Implement the redirectRequestToRegistrationPage() method by following these steps:
    1. Annotate the method with the @RequestMapping annotation and ensure that the method processes GET requests send to url ‘/signup’.
    2. Return a String ‘redirect:/user/register’. This will redirect the request to url ‘/user/register’.

The source code of the SignUpController class looks as follows:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class SignUpController {

    @RequestMapping(value = "/signup", method = RequestMethod.GET)
    public String redirectRequestToRegistrationPage() {
        return "redirect:/user/register";
    }
}

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:

  1. Create the controller class and annotate it with the @Controller annotation.
  2. 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.
  3. 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:
    1. Create a new RegistrationForm object.
    2. 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
      1. 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.
      2. 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.
      3. 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.
      4. Set the sign in provider to the form object by following these steps:
        1. Get the sign in provider by calling the getProviderId() method of the ConnectionKey class.
        2. Transform the String returned by the getProviderId() method to uppercase.
        3. 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).
        4. Set the returned value to the form object.
    3. Return the form object.
  4. 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:
    1. Annotate the method with the @RequestMapping annotation and ensure that controller method processes GET requests send to url ‘/user/register’.
    2. 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.
    3. Add a Model object as a method parameter.
    4. 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.
    5. Get the form object by calling the private createRegistrationDTO() method. Pass the Connection object as a method parameter.
    6. Set the form object to model as a model attribute called ‘user’.
    7. Return the name of the registration form view (‘user/registrationForm’).

The relevant part of the RegistrationController class looks as follows:

import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionKey;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;

@Controller
@SessionAttributes("user")
public class RegistrationController {

    @RequestMapping(value = "/user/register", method = RequestMethod.GET)
    public String showRegistrationForm(WebRequest request, Model model) {
        Connection<?> connection = ProviderSignInUtils.getConnection(request);

        RegistrationForm registration = createRegistrationDTO(connection);
        model.addAttribute("user", registration);

        return "user/registrationForm";
    }

    private RegistrationForm createRegistrationDTO(Connection<?> connection) {
        RegistrationForm dto = new RegistrationForm();

        if (connection != null) {
            UserProfile socialMediaProfile = connection.fetchUserProfile();
            dto.setEmail(socialMediaProfile.getEmail());
            dto.setFirstName(socialMediaProfile.getFirstName());
            dto.setLastName(socialMediaProfile.getLastName());

            ConnectionKey providerKey = connection.getKey();
            dto.setSignInProvider(SocialMediaService.valueOf(providerKey.getProviderId().toUpperCase()));
        }

        return dto;
    }
}

The next thing that we have to do is to create the JSP page. Let’s move on and find out how this is done.

Creating the JSP Page

We can create the JSP page which contains the registration form by following these steps:

  1. Ensure that the registration form is shown only to anonymous users. We can do this by following these steps:
    1. Wrap the login form and social sign in buttons inside the authorize tag of the Spring Security tag library.
    2. Set the value of the access attribute to isAnonymous().
  2. Implement the registration form by following these steps:
    1. Ensure that when the registration form is submitted, a POST request is send to url ‘/user/register’.
    2. Add a CSRF token to the request. This is required because we enabled the CSRF protection of Spring Security in the first part of this tutorial.
    3. If the sign in provider is found from the form object, add it to the form as a hidden field.
    4. Add a firstName field to the form and ensure that the validation errors concerning the firstName field are shown.
    5. Add a lastName field to the form and ensure that the validation errors concerning the lastName field are shown.
    6. Add an email field to the form and ensure that the validation errors concerning the email field are shown.
    7. If the user is creating a normal user account (the value of the form object’s signInProvider field is null), follow these steps:
      1. Add a password field to the form and ensure that the validation errors concerning the password field are shown.
      2. Add a passwordVerification field to the form and ensure that validation errors concerning the passwordVerification field are shown.
    8. Add a submit button to the form
  3. Ensure that a help message is shown if an authenticated user accesses the registration page. We can do this by following these steps:
    1. Wrap the error message area inside the authorize tag of the Spring Security tag library.
    2. Set the value of the access attribute to isAuthenticated().
    3. Get the localized error message by using the message tag of the Spring tag library.

Note: The Spring 3.2 reference manual has more information about the form tags of the Spring JSP tag library.

The source code of the registrationForm.jsp page looks as follows:

<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/app/user.form.js"></script>
</head>
<body>
    <div class="page-header">
        <h1><spring:message code="label.user.registration.page.title"/></h1>
    </div>
    <!--
        If the user is anonymous (not logged in), show the registration form.
    -->
    <sec:authorize access="isAnonymous()">
        <div class="panel panel-default">
            <div class="panel-body">
                <!--
                    Ensure that when the form is submitted, a POST request is send to url
                    '/user/register'.
                -->
                <form:form action="/user/register" commandName="user" method="POST" enctype="utf8" role="form">
                    <!-- Add CSRF token to the request. -->
                    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
                    <!--
                        If the user is using social sign in, add the signInProvider
                        as a hidden field.
                    -->
                    <c:if test="${user.signInProvider != null}">
                        <form:hidden path="signInProvider"/>
                    </c:if>
                    <div class="row">
                        <div id="form-group-firstName" class="form-group col-lg-4">
                            <label class="control-label" for="user-firstName"><spring:message code="label.user.firstName"/>:</label>
                            <!--
                                Add the firstName field to the form and ensure
                                that validation errors are shown.
                            -->
                            <form:input id="user-firstName" path="firstName" cssClass="form-control"/>
                            <form:errors id="error-firstName" path="firstName" cssClass="help-block"/>
                        </div>
                    </div>
                    <div class="row">
                        <div id="form-group-lastName" class="form-group col-lg-4">
                            <label class="control-label" for="user-lastName"><spring:message code="label.user.lastName"/>:</label>
                            <!--
                                Add the lastName field to the form and ensure
                                that validation errors are shown.
                            -->
                            <form:input id="user-lastName" path="lastName" cssClass="form-control"/>
                            <form:errors id="error-lastName" path="lastName" cssClass="help-block"/>
                        </div>
                    </div>
                    <div class="row">
                        <div id="form-group-email" class="form-group col-lg-4">
                            <label class="control-label" for="user-email"><spring:message code="label.user.email"/>:</label>
                            <!--
                                Add the email field to the form and ensure
                                that validation errors are shown.
                            -->
                            <form:input id="user-email" path="email" cssClass="form-control"/>
                            <form:errors id="error-email" path="email" cssClass="help-block"/>
                        </div>
                    </div>
                    <!--
                        If the user is creating a normal user account, add password fields
                        to the form.
                    -->
                    <c:if test="${user.signInProvider == null}">
                        <div class="row">
                            <div id="form-group-password" class="form-group col-lg-4">
                                <label class="control-label" for="user-password"><spring:message code="label.user.password"/>:</label>
                                <!--
                                    Add the password field to the form and ensure
                                    that validation errors are shown.
                                -->
                                <form:password id="user-password" path="password" cssClass="form-control"/>
                                <form:errors id="error-password" path="password" cssClass="help-block"/>
                            </div>
                        </div>
                        <div class="row">
                            <div id="form-group-passwordVerification" class="form-group col-lg-4">
                                <label class="control-label" for="user-passwordVerification"><spring:message code="label.user.passwordVerification"/>:</label>
                                <!--
                                    Add the passwordVerification field to the form and ensure
                                    that validation errors are shown.
                                -->
                                <form:password id="user-passwordVerification" path="passwordVerification" cssClass="form-control"/>
                                <form:errors id="error-passwordVerification" path="passwordVerification" cssClass="help-block"/>
                            </div>
                        </div>
                    </c:if>
                    <!-- Add the submit button to the form. -->
                    <button type="submit" class="btn btn-default"><spring:message code="label.user.registration.submit.button"/></button>
                </form:form>
            </div>
        </div>
    </sec:authorize>
    <!--
        If the user is authenticated, show a help message instead
        of registration form.
    -->
    <sec:authorize access="isAuthenticated()">
        <p><spring:message code="text.registration.page.authenticated.user.help"/></p>
    </sec:authorize>
</body>
</html>

Let’s move on and find out how we can process the submission of the registration form.

Processing the Form Submissions of the Registration Form

Our next step is to process the form submissions of the registration form. We can do this by following these steps:

  1. Validate the information entered to the registration form. If the information is not valid, we render the registration form and show validation error messages to the user.
  2. Ensure that the email address given by the user is unique. If the email address is not unique, we render the registration form and show an error message to the user.
  3. Create a new user account and log in the user.
  4. Redirect the user to the front page.

This process is illustrated in the following diagram:

social-registrationform-submit

Let’s start by implementing the controller method which processes the form submissions of the registration form.

Implementing the Controller Method

The controller method which processes the form submissions of the registration form has the following responsibilities:

  • It ensures that the information entered to the registration form is valid.
  • It informs the user if the email address entered to the registration form is found from the database.
  • It passes the form object forward to the service layer.
  • It persists the connection to the UserConnection table if the user is creating a new user account by using social sign in.
  • It logs the user in after a new user account has been created.

We can implement this controller method by making the following changes to the RegistrationController class:

  1. Add a private UserService field to the controller class.
  2. Add a constructor which takes a UserService object as a constructor argument to the RegistrationController class and implement it by following these steps:
    1. Annotate the constructor with the @Autowired annotation. This ensures that the dependencies of this bean are injected by using constructor injection.
    2. Set the value of service field.
  3. Add a private addFieldError() method to the controller class. This method is used to add binding errors to the binding result. The method parameters of this method are described in the following:
    1. The objectName parameter is the name of the form object.
    2. The fieldName parameter is the name of the form field which contains invalid value.
    3. The fieldValue parameter contains the value of the form field.
    4. The errorCode parameter is the error code of the field error.
    5. The result parameter is a BindingResult object.
  4. Implement the addFieldError() method by following these steps:
    1. Create a new FieldError object by using the method parameters.
    2. Add the created FieldError object to the binding result by calling the AddError() method of the BindingResult class.
  5. 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:
    1. Add a try-catch structure to the method and catch DuplicateEmailException objects.
    2. 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.
    3. 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.
  6. Add a public registerUserAccount() method to the controller class and implement it by following these steps:
    1. Annotate the method with the @RequestMapping annotation and ensure that the method processes POST request send to url ‘/user/register’.
    2. Add a RegistrationForm object as a method parameter and annotate it with the following annotations:
      1. Annotate the method parameter with the @Valid annotation. This ensures that the information of this object is validated before the controller method is called.
      2. Annotate the method parameter with the @ModelAttribute annotation and set its value to ‘user’ (this is the name of the form object).
    3. Add a BindingResult object as a method parameter.
    4. 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.
    5. If the binding result has errors, return the name of the form view.
    6. Call the private createUserAccount() method and pass the RegistrationForm and BindingResult objects as method parameters.
    7. 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.
    8. Log the created user in by calling the static loginInUser() method of the SecurityUtil class. Pass the created User object as a method parameter.
    9. 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.
    10. Redirect the user to the front page of our application by returning a String ‘redirect:/’. This will redirect the request to url ‘/’.

The relevant part of the RegistrationController class looks as follows:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;

import javax.validation.Valid;

@Controller
@SessionAttributes("user")
public class RegistrationController {

    private UserService service;

    @Autowired
    public RegistrationController(UserService service) {
        this.service = service;
    }

    @RequestMapping(value ="/user/register", method = RequestMethod.POST)
    public String registerUserAccount(@Valid @ModelAttribute("user") RegistrationForm userAccountData,
                                      BindingResult result,
                                      WebRequest request) throws DuplicateEmailException {
        if (result.hasErrors()) {
            return "user/registrationForm";
        }

        User registered = createUserAccount(userAccountData, result);

        if (registered == null) {
            return "user/registrationForm";
        }
        SecurityUtil.logInUser(registered);
        ProviderSignInUtils.handlePostSignUp(registered.getEmail(), request);

        return "redirect:/";
    }

    private User createUserAccount(RegistrationForm userAccountData, BindingResult result) {
        User registered = null;

        try {
            registered = service.registerNewUserAccount(userAccountData);
        }
        catch (DuplicateEmailException ex) {
            addFieldError(
                    "user",
                    "email",
                    userAccountData.getEmail(),
                    "NotExist.user.email",
                    result);
        }

        return registered;
    }

    private void addFieldError(String objectName, String fieldName, String fieldValue,  String errorCode, BindingResult result) {
        FieldError error = new FieldError(
                objectName,
                fieldName,
                fieldValue,
                false,
                new String[]{errorCode},
                new Object[]{},
                errorCode
        );

        result.addError(error);
    }
}

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:

  1. Create a new ExampleUserDetails object by using the information of the created user.
  2. Create a new UsernamePasswordAuthenticationToken object and pass the following arguments to its constructor:
    1. The first argument is the principal (aka logged in user). Pass the created ExampleUserDetails object as the first constructor argument.
    2. The second argument contains the credentials of the user. Pass null as the second constructor argument.
    3. The third argument contains the the authorities of the user. We can get the authorities by calling the getAuthorities() method of the ExampleUserDetails class.
  3. Set created Authentication object into security context by following these steps:
    1. Get the SecurityContext object by calling the static getContext() method of the SecurityContextHolder class.
    2. Call the static setAuthentication() method of the SecurityContext class and pass the created UsernamePasswordAuthenticationToken object as a method parameter.

The source code of the SecurityUtil class looks as follows:

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtil {

    public static void logInUser(User user) {
        ExampleUserDetails userDetails = ExampleUserDetails.getBuilder()
                .firstName(user.getFirstName())
                .id(user.getId())
                .lastName(user.getLastName())
                .password(user.getPassword())
                .role(user.getRole())
                .socialSignInProvider(user.getSignInProvider())
                .username(user.getEmail())
                .build();

        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
}

Note: 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.

Note: 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:

  1. Create an abstract BaseEntity class which has one type parameter called ID. This parameter is the type of the entity’s private key.
  2. Annotate the class with the @MapperSuperclass annotation. This means that the mapping information of the BaseEntity class is applied to its subclasses.
  3. Add a DateTime field called creationTime to the class and configure it by following these steps:
    1. Annotate the field with the @Column annotation and configure the name of the database column. The value of the nullable attribute to false.
    2. 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.
  4. Add a DateTime field called modificationTime to the class and configure it by using these steps:
    1. Annotate the field with the @Column annotation and set the name of the database column. Ensure that this column is not nullable.
    2. 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).
  5. 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.
  6. Add an abstract getId() method to the class. This method returns the id of the actual entity.
  7. 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.
  8. 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.

The source code of the BaseEntity class looks as follows:

import org.hibernate.annotations.Type;
import org.joda.time.DateTime;

import javax.persistence.*;

@MappedSuperclass
public abstract class BaseEntity<ID> {

    @Column(name = "creation_time", nullable = false)
    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    private DateTime creationTime;

    @Column(name = "modification_time", nullable = false)
    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    private DateTime modificationTime;

    @Version
    private long version;

    public abstract ID getId();

    //Other getters are omitted for the sake of clarity.

    @PrePersist
    public void prePersist() {
        DateTime now = DateTime.now();
        this.creationTime = now;
        this.modificationTime = now;
    }

    @PreUpdate
    public void preUpdate() {
        this.modificationTime = DateTime.now();
    }
}

Second, we have to create the User class. We can create this class following these steps:

  1. Create a User class which extends the BaseEntity class and give the type of its private key (Long) as a type parameter.
  2. Annotate the created class with the @Entity annotation.
  3. Annotate the created class with the @Table annotation and ensure that the user information is stored to a database table called ‘user_accounts’.
  4. Add a private id field to the class and set its type to Long. Configure the field by following these steps:
    1. Annotate the field with the @Id annotation. This annotation is used to specify the primary key of the entity.
    2. 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.
  5. 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:
    1. The email address is stored to the ‘email’ column of the ‘users’ table.
    2. The maximum length of the email address is 100 characters.
    3. The email address cannot be null.
    4. The email address must be unique.
  6. 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:
    1. The first name is stored to the ‘first_name’ column of the ‘users’ table.
    2. The maximum length of the first name is 100 characters.
    3. The first name cannot be null.
  7. 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:
    1. The last name is stored to the ‘last_name’ column of the ‘users’ table.
    2. The maximum length of the last name is 100 characters.
    3. The last name cannot be null.
  8. 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:
    1. The password is stored to the ‘password’ column of the ‘users’ table.
    2. The maximum length of the password is 255 characters.
  9. 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:
    1. The role is stored to the ‘role’ column of the ‘users’ table.
    2. The maximum length of the role is 20 characters.
    3. The role cannot be null.
  10. 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:
    1. The sign in provider is stored to the ‘sign_in_provider’ field of the ‘users’ table.
    2. The maximum length of the sign in provider is 20 characters.
  11. Add a public static inner class called Builder to the User class. Implement this class by following these steps:
    1. Add a User field to the class. This field holds a reference to the constructed User object.
    2. 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.
    3. 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.
    4. Add a build() method to the builder class. This method returns the created User object.
  12. Add a public static getBuilder() method to the User class. This method returns a new User.Builder object.

Note: You can get more information about the builder pattern by reading a blog post called The builder pattern in practice.

The source code of the User class looks as follows:

import javax.persistence.*;

@Entity
@Table(name = "user_accounts")
public class User extends BaseEntity<Long> {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "email", length = 100, nullable = false, unique = true)
    private String email;

    @Column(name = "first_name", length = 100,nullable = false)
    private String firstName;

    @Column(name = "last_name", length = 100, nullable = false)
    private String lastName;

    @Column(name = "password", length = 255)
    private String password;

    @Enumerated(EnumType.STRING)
    @Column(name = "role", length = 20, nullable = false)
    private Role role;

    @Enumerated(EnumType.STRING)
    @Column(name = "sign_in_provider", length = 20)
    private SocialMediaService signInProvider;

    //The constructor and getters are omitted for the sake of clarity

    public static Builder getBuilder() {
        return new Builder();
    }

    public static class Builder {

        private User user;

        public Builder() {
            user = new User();
            user.role = Role.ROLE_USER;
        }

        public Builder email(String email) {
            user.email = email;
            return this;
        }

        public Builder firstName(String firstName) {
            user.firstName = firstName;
            return this;
        }

        public Builder lastName(String lastName) {
            user.lastName = lastName;
            return this;
        }

        public Builder password(String password) {
            user.password = password;
            return this;
        }

        public Builder signInProvider(SocialMediaService signInProvider) {
            user.signInProvider = signInProvider;
            return this;
        }

        public User build() {
            return user;
        }
    }
}

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.

The source code of the UserService interface looks as follows:

public interface UserService {

    public User registerNewUserAccount(RegistrationForm userAccountData) throws DuplicateEmailException;
}

Second, we have to implement the UserService interface. We can do it by following these steps:

  1. Create a class which implements the UserService interface and annotate this class with the @Service annotation.
  2. Add a PasswordEncoder field to the created class.
  3. Add a UserRepository field to to created class.
  4. Add a constructor which takes PasswordEncoder and UserRepository objects as constructor arguments to the service class. Implement the constructor by following these steps:
    1. Annotate the constructor with the @Autowired annotation. This ensures that the dependencies of this bean are injected by using constructor injection.
    2. Set the values of passwordEncoder and repository fields.
  5. 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:
    1. 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.
    2. If a user is found, return true.
    3. If a user is not found, return false.
  6. 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:
    1. 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.
    2. If the user is creating a user account by using social sign in, return null.
  7. Add a registerNewUserAccount() method to the service class and implement it by following these steps:
    1. Annotate the method with the @Transactional annotation. This means that the method is executed “inside” a read-write transaction.
    2. 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.
    3. Obtain the encoded password by calling the private encodePassword() method. Pass the RegistrationForm object as a method parameter.
    4. 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
    5. 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.
    6. Create the User object.
    7. 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.
    8. Return the persisted object.

The source code of the RepositoryUserService class looks as follows:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class RepositoryUserService implements UserService {

    private PasswordEncoder passwordEncoder;

    private UserRepository repository;

    @Autowired
    public RepositoryUserService(PasswordEncoder passwordEncoder, UserRepository repository) {
        this.passwordEncoder = passwordEncoder;
        this.repository = repository;
    }

    @Transactional
    @Override
    public User registerNewUserAccount(RegistrationForm userAccountData) throws DuplicateEmailException {
        if (emailExist(userAccountData.getEmail())) {
            throw new DuplicateEmailException("The email address: " + userAccountData.getEmail() + " is already in use.");
        }

        String encodedPassword = encodePassword(userAccountData);

        User.Builder user = User.getBuilder()
                .email(userAccountData.getEmail())
                .firstName(userAccountData.getFirstName())
                .lastName(userAccountData.getLastName())
                .password(encodedPassword);

        if (userAccountData.isSocialSignIn()) {
            user.signInProvider(userAccountData.getSignInProvider());
        }

        User registered = user.build();

        return repository.save(registered);
    }

    private boolean emailExist(String email) {
        User user = repository.findByEmail(email);

        if (user != null) {
            return true;
        }

        return false;
    }

    private String encodePassword(RegistrationForm dto) {
        String encodedPassword = null;

        if (dto.isNormalRegistration()) {
            encodedPassword = passwordEncoder.encode(dto.getPassword());
        }

        return encodedPassword;
    }
}

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:

  1. 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.
  2. 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.

Note: If you want to get more information about Spring Data JPA, you can take a look at my Spring Data JPA tutorial.

The source code of the UserRepository interface looks as follows:

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {

    public User findByEmail(String email);
}

That was it! Let’s move on and spend a moment to summarize what we have achieved during this blog post.

The Summary

We have now implemented the requirements of our example application. This means that

  • We have created a registration function which supports both “normal” user accounts and user accounts created by using social sign.
  • The users of our application can log in by using username and password.
  • The users of our application can log in by using social sign in.

Let’s refresh our memories and take a look at the registration process. This process is illustrated in the following figure:

social-signin-flow

This blog post has taught us the following things:

  • We learned how we can start the social sign in flow.
  • We learned how we can pre-populate the field of our registration form by using the information provided by the SaaS API provider.
  • We learned how we can create custom validation constraints which ensures that information entered to the registration form is valid.

The next part of this tutorial describes how we can write unit tests for the web layer of our application.

P.S. The example application of this blog post is available at Github.

If you enjoy reading similar content, you should follow me on Twitter:

About the Author

Petri Kainulainen is passionate about software development and continuous improvement. He specializes in software development with the Spring Framework and is the author of Spring Data book.

About Petri Kainulainen →

60 comments… add one

  • I am facing this problem when trying to run on server tomcat.

    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.social.connect.UsersConnectionRepository] is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean (DefaultListableBeanFactory.java:295)
    at org.springframework.context.support.AbstractApplicationContext.getBean (AbstractApplicationContext.java:1125)
    at org.springframework.social.security.SpringSocialConfigurer.getDependency (SpringSocialConfigurer.java:87)

    Reply
    • Thanks for point this problem out!

      I think that might be related to the changes which were made to configuration of Spring Social 1.1.0. I updated the Java configuration to use the new configuration scheme but it seems that it is not working on Tomcat.

      I will investigate this problem.

      Reply
      • 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.

        Reply
  • Petri another java guru suggested to remove @Profile(“application”) in the class SocialContext.java. That has fixed the problem in Apache Tomcat.

    Reply
    • 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 also possible to configure the Tomcat to use the correct Spring profile. This blog post describes how you can use Spring profiles with Tomcat.

      I will add these instructions to the README of my example application. Again, thanks for pointing this out!

      Reply
  • Hi Petri,
    Your post is so detail, I like it very much. I’ve a question, do you know where can I find the doc for SpringSocialConfigurer ? Thanks

    Reply
    • Hi Alex,

      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?

      Reply
  • Hi Petri,
    Thanks for your prompt reply, actually, I want to know its APIs, I wonder where to configure the URL for “/auth/facebook” and “/auth/twitter” or it’s fixed ?

    Best Regards,
    Alex

    Reply
  • i am also getting below error…
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.social.connect.UsersConnectionRepository] is defined

    Is it possible to do it normal way…with out creating spring profile in tomcat. never did that..

    sai

    Reply
  • Hi Petri,

    I have downloaded codes. Deployed codes, but getting above error.
    Also, how to use XML configuration without java?

    I see config files, but no web.xml.

    please help.
    sai

    Reply
    • Are you referring to the error which occurred because the active Spring profile wasn’t specified? If so, check out my answer to that comment.

      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

      • Load the context configuration
      • Configure the dispatcher servlet
      • Configure the required servlet filters
      • Configure the context loader listener

      Here are some links to useful resources:

      Reply
  • Hi Petri,

    I am just new for java config thingy. need your help. Do you have any steps that i can integrate into current files?

    How do i add below information in spring social. Do i need to modify ExampleApplicationConfig file? or what are files that i need to modify to get pass over current error or spring profiles to work.

    spring.profiles.active
    ${spring.profiles.active}

    spring.profiles.active=${spring.profiles.active}

    Reply
    • Hi Sai,

      there are two solution to this problem:

      1. 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.
      2. 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.
      Reply
  • Hi Petri,

    removed @profile. it works fine…

    thank you,
    Sridhar

    Reply
    • 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.

      Reply
  • Sorry to bug you.. so many times..
    now i am able to see home page but no buttons are displayed.i think site mesh is displaying body..

    Reply
  • please ignore my comments. application is working fine. great tutorial.

    sai

    Reply
    • I am happy to hear that you could solve your problems!

      Reply
  • Hi Pete,

    Once, user logs in through facebook(social), if user exists based on email address, is it possible to authenticate him with spring security?

    sai

    Reply
  • how do we handle, where after social sign in, where use account exists. i want to authorize user, instead of again prompting for user id and password. Any pointers?

    Reply
    • The approach has two problems:

      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.

      Unfortunately I am not sure what could be the “hacky” way to do this.

      Reply
  • I downloaded the code from git . But when I do mvn clean install it gives the following error

    Caused by: java.io.FileNotFoundException:
    spring-social-examples/sign-in/spring-mvc-normal/profiles/dev/socialConfig.properties

    Please help me I am stuck

    Reply
    • You have to create that file yourself and follow these steps:

      1. Add the Facebook application id and application secret to the properties file.
      2. Add the Twitter consumer key and consumer secret to the properties file.

      This is also described in the README of the example application.

      I hope that this answered to your question.

      Reply
  • Hi,

    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)


    Reply
    • 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.

      Reply
  • 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!

    Reply
    • Hi Liu,

      Does the email address or password of the user contain UTF-8 characters?

      Reply
      • There are NOT UTF-8 characters in the email address or password.
        I add the following code in login.jsp:

        Reason:

        Then the error shows: No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken

        Reply
      • Hi Petri,

        I solved the problem.

        1. I used configure(AuthenticationManagerBuilder auth) method instead of registerAuthentication(AuthenticationManagerBuilder auth) in the WebSecurityConfigurerAdapter class.

        2. Extra property was added to the dataSource in the PersistenceContext class:

        
        Properties prop = new Properties();
        prop.put("useUnicode", "true");
        prop.put("characterEncoding", "UTF-8");
        ......
        dataSource.setDriverProperties(prop);
        

        Now, I can login and get correct UTF-8 characters in the display pages.

        Reply
        • Hi,

          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.

          Thanks for pointing these problems out!

          Reply
          • Yeah, I forgot that. I really used Spring Security 3.2.0.RELEASE instead of 3.2.0.RC1.

          • 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.

            I updated the example application and my blog post yesterday.

            Again, thanks for pointing this problem out!

  • Hi Petri,

    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)

    Update: I removed the unrelevant parts from the stacktrace. – Petri

    Reply
    • Hi,

      I think that this question has been asked before. Did you check out my answer to that question?

      I just tested the following use cases:

      • Register a new user account by using Twitter.
      • Login by using Twitter.

      Both of these use cases are working. Have you compared the example application of this blog post with your application?

      Reply
  • Thanks for the perfect post, Petri, works like a charm!

    Reply
    • You are welcome!

      Reply
  • 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….

    Stackoverflow question :
    http://stackoverflow.com/questions/20664846/user-registration-login-sso-using-spring-security-oauth-2-0

    I did implemented the same use case using Spring OpenId.
    The Spring security namespace has tag that takes care of the configuration.

    I am trying to figure out its equivalent tag.

    Thanks for your help.

    Reply
  • Petri,

    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.

    java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction

    It seams like the autologin or logout is updating the persistent_logins table and not committing its work. Have you seen this before? How would you go about diagnosing/fixing this issue?

    Reply
    • Hi,

      I haven’t seen this before but I could try reproduce this when I have got time to do it (probably during the weekend). Can I reproduce this issue by following these steps:

      1. Login and select ‘remember me’
      2. Restart server
      3. Use cookie login

      By the way, have you configured the logout function to remove the remember me cookie? If you haven’t done this, it can cause some problems but to be honest, I am not sure if this is one of them.

      Reply
      • Petri,

        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.

        Thanks again…

        -Jeff

        Reply
        • Hi Jeff,

          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).

          Reply
        • Hi Jeff,

          I wasn’t able to reproduce your problem. I made the following the changes to the example application:

          1. Updated Spring Framework to version 4.0.0
          2. Updated Apache HttpClient to version 4.3.2
          3. Configured the remember me function by using Java configuration.

          You can get my version of the example application from Github (I created a new branch for it).

          It would be interesting to know if I missed something.

          Reply
          • Petri,

            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.

            Thanks again…

          • Jeff,

            I will try to reproduce this issue today by following your new instructions.

          • Jeff,

            for some reason I cannot reproduce this problem by following the steps you gave in your last comment. What database are you using? I am using MySQL 5.6.10.

  • Hi Petri,

    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.

    Reply
  • 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 ?

    Reply
    • This is an Eclipse specific problem (See this M2E wiki page for more details).

      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.

      Reply
  • Hi,

    I would like to add a social login option without being redirected to the registration form.
    What should I do?

    Best,
    Shahar

    Reply
    • 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:

      1. Create a service method which saves a new user account to the database.
      2. 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).
      3. Call the service method which you created in step 1.
      4. Log the created user in (You can use the static logInUser() method of the SecurityUtil class for this purpose).
      5. Persist the connection to the UserConnection database table by calling the static handlePostSignUp() method of the ProviderSignInUtils class.
      6. 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.

      I hope that this answered to your question.

      Reply
  • Hi Petrik,

    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?

    Regards
    Cassio

    Reply
    • Hi Cassio,

      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:

      
      .and()
      	.authorizeRequests()
      		//Anyone can access these urls
      		.antMatchers(
      			"/auth/**",
      			//This grants access to your directory
      			"/foo/**",
      			"/login",
      			"/signin/**",
      			"/signup/**",
      			"/user/register/**"
      		).permitAll()
      		//The rest of the our application is protected.
      		.antMatchers("/**").hasRole("USER")
      
      

      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:

      Reply
      • 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.

        Cheers

        Reply
        • Hi Cassio,

          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. :)

          Reply
          • Hi Petri,

            Yesterday I have been in travel, now I saw your link about SpringBoot and appreciate your help.

            Thks so much, best regards!

Leave a Comment