Add social based login (Google, Facebook, and Github) to your Spring Boot application using OAuth2 functionalities

In the tutorial, we will explain how to add social-based login to a Spring boot application using a Spring Security function called OAuth2. We use MySQL database and React for the frontend.

App Screenshot

Creating the Project

You can create a project using the Spring Initializr web tool, follows the introduction to fill in the information:

  • Artifact: ozenero-spring-social
  • Dependencies: Spring Web, Spring Security, OAuth2 Client, Spring Data JPA, MySQL Driver, Validation

After that, you can click Generate and download your project

Creating OAuth2 apps for social login

You need to create an app in OAuth2 provider console to enable social login with an OAuth2 provider. After that, you can get AppID and AppSecret (also called ClientId and Client Secret). OAuth2 providers use the AppID and AppSecret to identify your app. Some other settings include:

  • Authorized redirect URIs: A valid list of redirect URIs to redirect users after granting or rejecting permission to the app.
  • Scope: used to ask users for permission to access data.

Creating Facebook, Github, and Google Apps

Configuring the Spring Boot application

By default, Spring boot reads configurations from the file src/main/resource/ It also supports .yaml format. Rename file to application.yaml and add the following configurations.

        url: jdbc:mysql://localhost:3306/spring_social?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
        username: root
        password: callicoder

        show-sql: true
            ddl-auto: update
            naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
                dialect: org.hibernate.dialect.MySQL5InnoDBDialect
              clientSecret: your_secret
              redirectUri: "{baseUrl}/oauth2/callback/{registrationId}"
                - email
                - profile
              clientId: your_id
              clientSecret: your_secret
              redirectUri: "{baseUrl}/oauth2/callback/{registrationId}" # Note that facebook now mandates the use of https redirect URIs, so make sure your app supports https in production
                - email
                - public_profile
              clientId: your_id
              clientSecret: your_secret
              redirectUri: "{baseUrl}/oauth2/callback/{registrationId}"
                - user:email
                - read:user
    tokenSecret: your_token_secret
    tokenExpirationMsec: 864000000
    allowedOrigins: http://localhost:3000 # Comma separated list of allowed origins
    # After successfully authenticating with the OAuth2 Provider,
    # we'll be generating an auth token for the user and sending the token to the
    # redirectUri mentioned by the client in the /oauth2/authorize request.
    # We're not using cookies because they won't work well in mobile clients.
      - http://localhost:3000/oauth2/redirect
      - myandroidapp://oauth2/redirect
      - myiosapp://oauth2/redirect

The data source includes MySQL database configurations. Database name is spring_social, please modify spring.datasource.username and spring.datasource.password.

In security:oauth2:client:registration:, the configurations include all details of oauth2 providers. Inapp.auth, its config the JWT authentication token when the user logged in successfully.

In redirectUriTemplate property in all the registered oauth2 providers, when you create an app in the OAuth2 providers, you have to add an authorized redirect URI which matches the template. In this case, for a google app, we config the authorizedRedirectURI http://localhost:8080/oauth2/callback/google.

Binding AppProperties

In the next step, we bind all configurations prefixed with app to a POJO class using Spring Boot’s @ConfigurationProperties feature

package com.example.springsocial.config;


import java.util.ArrayList;
import java.util.List;

@ConfigurationProperties(prefix = "app")
public class AppProperties {
    private final Auth auth = new Auth();
    private final OAuth2 oauth2 = new OAuth2();

    public static class Auth {
        private String tokenSecret;
        private long tokenExpirationMsec;

        public String getTokenSecret() {
            return tokenSecret;

        public void setTokenSecret(String tokenSecret) {
            this.tokenSecret = tokenSecret;

        public long getTokenExpirationMsec() {
            return tokenExpirationMsec;

        public void setTokenExpirationMsec(long tokenExpirationMsec) {
            this.tokenExpirationMsec = tokenExpirationMsec;

    public static final class OAuth2 {
        private List<String> authorizedRedirectUris = new ArrayList<>();

        public List<String> getAuthorizedRedirectUris() {
            return authorizedRedirectUris;

        public OAuth2 authorizedRedirectUris(List<String> authorizedRedirectUris) {
            this.authorizedRedirectUris = authorizedRedirectUris;
            return this;

    public Auth getAuth() {
        return auth;

    public OAuth2 getOauth2() {
        return oauth2;

Enabling AppProperties

In order to enable the properties, we add the@EnableConfigurationProperties annotation. Let’s open the main application class and add the annotation like below.

package com.example.springsocial;

import com.example.springsocial.config.AppProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class SpringSocialApplication {

	public static void main(String[] args) {, args);

Enabling CORS

In order to enable CORS to allow our frontend client can access the APIs from a different origin. We need to enable the origin http://localhost:3000 where the frontend application will be running.

package com.example.springsocial.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

public class WebMvcConfig implements WebMvcConfigurer {

    private final long MAX_AGE_SECS = 3600;

    private String[] allowedOrigins;

    public void addCorsMappings(CorsRegistry registry) {
        .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")

Creating the database entities

Let’s now create the Entity classes of our application. Following is the definition of the User class –

In the next step, we create Entity classes for the application. You can define the User class like below.

package com.example.springsocial.model;
import com.fasterxml.jackson.annotation.JsonIgnore;

import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;

@Table(name = "users", uniqueConstraints = {
        @UniqueConstraint(columnNames = "email")
public class User {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String email;

    private String imageUrl;

    @Column(nullable = false)
    private Boolean emailVerified = false;

    private String password;

    private AuthProvider provider;

    private String providerId;

    // Getters and Setters (Omitted for brevity)

The User class contains information about the authentication provider. Following is the definition of the AuthProvider enum –

In the User class, it provides information related to the authentication provider. Here is the definition of the AuthProvider enum.

package com.example.springsocial.model;

public enum  AuthProvider {

Creating the repositories for accessing data from the database

Let’s create the repository layer for accessing data from the database. The following UserRepository interface provides database functionalities for the User entity. Thanks to Spring-Data-JPA, we don’t need to write much code here

In order to create the repository layer for accessing data from the database, we need to config theUserRepository interface to provide database functionalities for the User entity. Refer to Spring-Data-JPA  for the code

package com.example.springsocial.repository;

import com.example.springsocial.model.User;
import org.springframework.stereotype.Repository;

import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {

    Optional<User> findByEmail(String email);

    Boolean existsByEmail(String email);


In this article, we introduce how to configure an application and defined the entity classes and repositories.

79 thoughts on “Add social based login (Google, Facebook, and Github) to your Spring Boot application using OAuth2 functionalities”

  1. Good day, I simply hopped over on your website online by way of StumbleUpon. No longer something I’d usually learn, but I preferred your thoughts none the less. Thank you for making one thing price reading.

  2. Cheapest speeches and toasts, as well as toasts. probably are created building your own at the party and will be most likely to turn into witty, humorous so new even. best man toast

  3. Revenue Administration Inheritance and Gift Tax Declaration Application … To benefit from this service, you must use the following authentication methods.

  4. The next time I just read a blog, I hope which it doesnt disappoint me as much as this blog. I mean, It was my choice to read, but I just thought youd have some thing intriguing to talk about. All I hear can be a bunch of whining about something that you could fix when you werent too busy looking for attention.

  5. First Of All, let me commend your clearness on this subject. I am not an expert on this topic, but after registering your article, my understanding has developed well. Please permit me to take hold of your rss feed to stay in touch with any potential updates. Solid job and will pass it on to supporters and my online readers.

  6. Hmm is anyone else having problems with the images on this blog loading? I’m trying to figure out if its a problem on my end or if it’s the blog. Any responses would be greatly appreciated.

  7. I’ve recently started a site, the info you provide on this website has helped me tremendously. Thank you for all of your time & work. “‘Tis our true policy to steer clear of permanent alliances with any portion of the foreign world.” by George Washington.

  8. Thanks , I have just been looking for information about this topic for ages and yours is the greatest I have discovered so far. But, what about the bottom line? Are you sure about the source?

  9. Hello, Neat post. There is a problem together with your website in web explorer, might check thisK IE still is the market leader and a huge element of other people will pass over your magnificent writing due to this problem.

  10. Hi, Neat post. There is a problem along with your web site in internet explorer, would test this?K IE still is the market leader and a huge element of people will pass over your magnificent writing due to this problem.

  11. Howdy! I know this is kinda off topic however I’d figured I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa? My website goes over a lot of the same subjects as yours and I feel we could greatly benefit from each other. If you happen to be interested feel free to shoot me an e-mail. I look forward to hearing from you! Great blog by the way!

  12. You can definitely see your enthusiasm in the work you write. The world hopes for more passionate writers like you who are not afraid to say how they believe. Always go after your heart.

  13. I have been exploring for a bit for any high-quality articles or weblog posts in this kind of house . Exploring in Yahoo I eventually stumbled upon this web site. Studying this info So i’m happy to convey that I’ve a very good uncanny feeling I discovered exactly what I needed. I so much no doubt will make certain to don’t overlook this site and give it a glance regularly.

  14. Hiya, I am really glad I’ve found this information. Nowadays bloggers publish only about gossips and web and this is really annoying. A good site with exciting content, this is what I need. Thank you for keeping this web-site, I will be visiting it. Do you do newsletters? Can not find it.

  15. I used to be more than happy to find this net-site.I wanted to thanks for your time for this excellent read!! I positively enjoying every little bit of it and I have you bookmarked to take a look at new stuff you weblog post.

  16. I have not checked in here for a while because I thought it was getting boring, but the last several posts are great quality so I guess I’ll add you back to my daily bloglist. You deserve it my friend 🙂

  17. Hey! I know this is somewhat off topic but I was wondering if you knew where I could get a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble finding one? Thanks a lot!

  18. You can certainly see your expertise in the work you write. The world hopes for even more passionate writers like you who are not afraid to say how they believe. Always go after your heart.

  19. hi!,I love your writing so a lot! share we keep in touch more approximately your post on AOL? I need an expert on this area to unravel my problem. May be that’s you! Looking forward to peer you.

  20. Good V I should definitely pronounce, impressed with your web site. I had no trouble navigating through all tabs and related info ended up being truly simple to do to access. I recently found what I hoped for before you know it at all. Quite unusual. Is likely to appreciate it for those who add forums or anything, site theme . a tones way for your customer to communicate. Nice task..

  21. I’ve recently started a website, the info you offer on this web site has helped me greatly. Thanks for all of your time & work. “The inner fire is the most important thing mankind possesses.” by Edith Sodergran.

  22. I would like to thnkx for the efforts you have put in writing this blog. I am hoping the same high-grade blog post from you in the upcoming as well. In fact your creative writing abilities has inspired me to get my own blog now. Really the blogging is spreading its wings quickly. Your write up is a good example of it.

  23. Thanks for every other fantastic article. The place else may just anyone get that kind of information in such an ideal manner of writing? I have a presentation subsequent week, and I’m on the search for such info.

  24. A lot of thanks for every one of your work on this blog. Gloria really likes setting aside time for internet research and it’s easy to see why. Almost all know all regarding the dynamic tactic you make good techniques via the web blog and as well as attract participation from other people on that topic then our favorite child is undoubtedly being taught a lot of things. Enjoy the remaining portion of the new year. Your carrying out a good job.

  25. Just want to say your article is as amazing. The clearness in your post is just cool and i could assume you are an expert on this subject. Well with your permission let me to grab your feed to keep up to date with forthcoming post. Thanks a million and please keep up the enjoyable work.

  26. Greetings! I know this is kinda off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one? Thanks a lot!

  27. I think other web site proprietors should take this web site as an model, very clean and great user friendly style and design, as well as the content. You’re an expert in this topic!

  28. I would like to thnkx for the efforts you have put in writing this blog. I am hoping the same high-grade blog post from you in the upcoming as well. In fact your creative writing abilities has inspired me to get my own blog now. Really the blogging is spreading its wings quickly. Your write up is a good example of it.

  29. Thank you, I’ve recently been looking for info approximately this topic for a while and yours is the greatest I have came upon so far. However, what about the conclusion? Are you sure about the source?

  30. You could certainly see your enthusiasm in the work you write. The arena hopes for more passionate writers such as you who aren’t afraid to say how they believe. At all times follow your heart.

  31. Good post. I be taught one thing more challenging on different blogs everyday. It’ll always be stimulating to read content from different writers and observe a little something from their store. I’d choose to use some with the content on my weblog whether you don’t mind. Natually I’ll provide you with a hyperlink on your internet blog. Thanks for sharing.

  32. I’d have to examine with you here. Which is not one thing I usually do! I take pleasure in reading a post that may make folks think. Additionally, thanks for permitting me to comment!

  33. I was just seeking this information for a while. After 6 hours of continuous Googleing, finally I got it in your web site. I wonder what’s the lack of Google strategy that don’t rank this type of informative websites in top of the list. Normally the top websites are full of garbage.

  34. I was wondering if you ever considered changing the layout of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 pictures. Maybe you could space it out better?

  35. A person necessarily help to make severely posts I might state.That is the first time I frequented your website page and so far?I surprised with the research you made to make this actual putup amazing. Magnificent task!

Leave a Reply

Your email address will not be published. Required fields are marked *