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.
Creating the Project
You can create a project using the Spring Initializr web tool http://start.spring.io, 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
- Facebook App: Facebook app can be created at Facebook apps dashboard
- Github App: Github apps can be created at https://github.com/settings/apps.
- Google Project: Google Project and the credentials for OAuth2 can be created at Google Developer Console
Configuring the Spring Boot application
By default, Spring boot reads configurations from the file src/main/resource/application.properties
. It also supports .yaml
format. Rename application.properties
file to application.yaml
and add the following configurations.
spring:
datasource:
url: jdbc:mysql://localhost:3306/spring_social?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
username: root
password: callicoder
jpa:
show-sql: true
hibernate:
ddl-auto: update
naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
security:
oauth2:
client:
registration:
google:
clientId: your_id.apps.googleusercontent.com
clientSecret: your_secret
redirectUri: "{baseUrl}/oauth2/callback/{registrationId}"
scope:
- email
- profile
facebook:
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
scope:
- email
- public_profile
github:
clientId: your_id
clientSecret: your_secret
redirectUri: "{baseUrl}/oauth2/callback/{registrationId}"
scope:
- user:email
- read:user
provider:
facebook:
authorizationUri: https://www.facebook.com/v3.0/dialog/oauth
tokenUri: https://graph.facebook.com/v3.0/oauth/access_token
userInfoUri: https://graph.facebook.com/v3.0/me?fields=id,first_name,middle_name,last_name,name,email,verified,is_verified,picture.width(250).height(250)
app:
auth:
tokenSecret: your_token_secret
tokenExpirationMsec: 864000000
cors:
allowedOrigins: http://localhost:3000 # Comma separated list of allowed origins
oauth2:
# 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.
authorizedRedirectUris:
- 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 org.springframework.boot.context.properties.ConfigurationProperties;
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 SpringSocialApplication.java
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;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties(AppProperties.class)
public class SpringSocialApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSocialApplication.class, 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;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private final long MAX_AGE_SECS = 3600;
@Value("${app.cors.allowedOrigins}")
private String[] allowedOrigins;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(allowedOrigins)
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(MAX_AGE_SECS);
}
}
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;
@Entity
@Table(name = "users", uniqueConstraints = {
@UniqueConstraint(columnNames = "email")
})
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Email
@Column(nullable = false)
private String email;
private String imageUrl;
@Column(nullable = false)
private Boolean emailVerified = false;
@JsonIgnore
private String password;
@NotNull
@Enumerated(EnumType.STRING)
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 {
local,
facebook,
google,
github
}
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.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
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.
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.
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
It is rather grateful for the help in this question, can, I too can help you something?
Revenue Administration Inheritance and Gift Tax Declaration Application … To benefit from this service, you must use the following authentication methods.
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.
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.
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.
Best free games pet simulator x game roblox scripts and codes here now. Pet simulator x codes.
I dont know if I see where you are comming from, but do indeed elaborate a little more. Thanks
I view something really special in this website.
Excellent site. Lots of helpful info here. I?¦m sending it to some friends ans additionally sharing in delicious. And obviously, thanks to your effort!
Hello.This article was extremely remarkable, particularly since I was investigating for thoughts on this topic last Wednesday.
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.
Hello There. I discovered your blog the usage of msn. This is a really well written article. I’ll make sure to bookmark it and return to read extra of your helpful info. Thanks for the post. I’ll definitely comeback.
I reckon something really interesting about your website so I saved to fav.
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?
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.
I think this internet site has got some real excellent info for everyone. “A kiss, is the physical transgression of the mental connection which has already taken place.” by Tanielle Naus.
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.
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!
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.
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.
I have learn some good stuff here. Definitely worth bookmarking for revisiting. I wonder how so much effort you place to create the sort of magnificent informative website.
You are my inhalation, I own few web logs and sometimes run out from to brand : (.
Some times its a pain in the ass to read what blog owners wrote but this website is rattling user pleasant! .
I enjoy the efforts you have put in this, regards for all the great posts.
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.
Sweet internet site, super layout, really clean and apply genial.
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.
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 🙂
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!
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.
After all, what a great site and informative posts, I will upload inbound link – bookmark this web site? Regards, Reader.
Wonderful web site. A lot of useful information here. I am sending it to a few friends ans additionally sharing in delicious. And certainly, thank you in your effort!
Appreciate you sharing, great article.Much thanks again. Really Cool.
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.
Hello.This post was really interesting, especially since I was searching for thoughts on this matter last Saturday.
It’s actually a great and helpful piece of information. I’m satisfied that you just shared this useful info with us. Please keep us informed like this. Thank you for sharing.
I have recently started a web site, the information you offer on this website has helped me tremendously. Thank you for all of your time & work.
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..
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.
Some really interesting info , well written and generally user genial.
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.
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.
Perfectly written articles, Really enjoyed looking through.
I carry on listening to the news bulletin speak about getting boundless online grant applications so I have been looking around for the finest site to get one. Could you advise me please, where could i find some?
I’ll right away grab your rss feed as I can’t find your e-mail subscription link or newsletter service. Do you’ve any? Please let me know so that I could subscribe. Thanks.
This website online can be a walk-by for all the information you wanted about this and didn’t know who to ask. Glimpse right here, and also you’ll positively discover it.
I like this website because so much useful material on here : D.
If you want to get the latest gaming news, you can visit my page on Zupyak.
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.
Great amazing issues here. I?¦m very happy to look your post. Thanks a lot and i’m having a look forward to touch you. Will you kindly drop me a mail?
I have read several good stuff here. Definitely worth bookmarking for revisiting. I wonder how much effort you put to create such a fantastic informative website.
This website was… how do you say it? Relevant!! Finally I’ve found something that helped me. Thanks!
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.
I couldn’t resist commenting
Hi there, You’ve performed an incredible job. I will definitely digg it and personally recommend to my friends. I am sure they’ll be benefited from this web site.
Only a smiling visitant here to share the love (:, btw great layout.
I’m not sure why but this blog is loading very slow for me. Is anyone else having this issue or is it a problem on my end? I’ll check back later on and see if the problem still exists.
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!
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!
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.
Real wonderful info can be found on blog. “You have to learn that if you start making sure you feel good, everything will be okay.” by Ruben Studdard.
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?
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.
Hey there just wanted to give you a brief heads up and let you know a few of the images aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same outcome.
There is apparently a bundle to know about this. I feel you made various nice points in features also.
Hello! I just would like to give a huge thumbs up for the great info you have here on this post. I will be coming back to your blog for more soon.
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.
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!
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.
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?
Your place is valueble for me. Thanks!…
Spot on with this write-up, I really think this website wants rather more consideration. I’ll in all probability be again to read far more, thanks for that info.
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!
As a Newbie, I am constantly searching online for articles that can benefit me. Thank you
You should take part in a contest for one of the best blogs on the web. I will recommend this site!
I want to to thank you for this good read!! I certainly enjoyed every little bit of it. I’ve got you book marked to look at new things you post…
WONDERFUL Post.thanks for share..more wait .. …