Create a Facebook App & Login with that in Spring Social and Spring Boot

In this blog we will create our own app and with the help of our own appId and appSecret we will login and fetch some user related data also

So follow below steps to create your own facebook app

Step 1 – Login to developers facebook

5

Step 2 – Under my apps click on Add New App link

7

It will ask you to give display name and email and click on Create App ID button

6

Step 3 – Once app creation is done, you can see dashboard like below image

8

click on setting -> basic

9

so now you can see app id and app secret key.

Add Site URL (http://localhost:8080/) under website section.

10

click on Facebook Login -> Quickstart add website URL in Site URL text box and click on save

11

now we are ready to use this app

Lets start –

Download spring social facebook sample

application.properties

spring.social.facebook.appId=828571534198011
spring.social.facebook.appSecret=92a5af89dcd2d11d73a3e41f46d88ecd

HelloController.java

package hello;

import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/")
public class HelloController {

    private Facebook facebook;
    private Connection<Facebook> connection;
    private ConnectionRepository connectionRepository;

    public HelloController(Facebook facebook, ConnectionRepository connectionRepository) {
        this.facebook = facebook;
        this.connectionRepository = connectionRepository;
    }

    @GetMapping
    public String helloFacebook(Model model) {
        connection = connectionRepository.findPrimaryConnection(Facebook.class);
        if (connection == null) {
            return "redirect:/connect/facebook";
        } else {
            facebook = connection.getApi();
            String[] fields = { "id", "name" };
            model.addAttribute("isAuthorized", facebook.isAuthorized());
            model.addAttribute("userProfile", facebook.fetchObject("me", User.class, fields));
            return "hello";
        }
    }
}

hello.html

<html>
	<head>
		<title>Hello Facebook</title>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
	</head>
	<body>
		<h3>Authorize : <span th:text="${isAuthorized}">Authorize</span></h3>
		<h3>Name, <span th:text="${userProfile.name}">Name</span>!</h3>
	</body>
</html>

Start the server

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.10.RELEASE)

2018-09-05 14:38:46.457 INFO 14888 --- [ main] hello.Application : Starting Application on INR1601079 with PID 14888 (started by jeetp in C:\Users\jeetp\Downloads\Recycle Bin\gs-accessing-facebook-master\complete)
2018-09-05 14:38:46.466 INFO 14888 --- [ main] hello.Application : No active profile set, falling back to default profiles: default
2018-09-05 14:38:47.384 INFO 14888 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@78b1cc93: startup date [Wed Sep 05 14:38:47 IST 2018]; root of context hierarchy
2018-09-05 14:38:49.119 INFO 14888 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-09-05 14:38:49.906 INFO 14888 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 9090 (http)
2018-09-05 14:38:49.931 INFO 14888 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-09-05 14:38:49.932 INFO 14888 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-09-05 14:38:50.147 INFO 14888 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-09-05 14:38:50.147 INFO 14888 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2787 ms
2018-09-05 14:38:50.451 INFO 14888 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-09-05 14:38:50.458 INFO 14888 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-09-05 14:38:50.459 INFO 14888 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-09-05 14:38:50.459 INFO 14888 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-09-05 14:38:50.460 INFO 14888 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-09-05 14:38:50.933 INFO 14888 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@78b1cc93: startup date [Wed Sep 05 14:38:47 IST 2018]; root of context hierarchy
2018-09-05 14:38:51.022 INFO 14888 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET]}" onto public java.lang.String hello.HelloController.helloFacebook(org.springframework.ui.Model)
2018-09-05 14:38:51.025 INFO 14888 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-09-05 14:38:51.026 INFO 14888 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-09-05 14:38:51.041 INFO 14888 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/connect/{providerId}],methods=[POST]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.connect(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
2018-09-05 14:38:51.041 INFO 14888 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/connect/{providerId}],methods=[DELETE]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.removeConnections(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
2018-09-05 14:38:51.042 INFO 14888 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/connect/{providerId}],methods=[GET],params=[error]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth2ErrorCallback(java.lang.String,java.lang.String,java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
2018-09-05 14:38:51.042 INFO 14888 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/connect/{providerId}],methods=[GET]}" onto public java.lang.String org.springframework.social.connect.web.ConnectController.connectionStatus(java.lang.String,org.springframework.web.context.request.NativeWebRequest,org.springframework.ui.Model)
2018-09-05 14:38:51.042 INFO 14888 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/connect],methods=[GET]}" onto public java.lang.String org.springframework.social.connect.web.ConnectController.connectionStatus(org.springframework.web.context.request.NativeWebRequest,org.springframework.ui.Model)
2018-09-05 14:38:51.042 INFO 14888 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/connect/{providerId}],methods=[GET],params=[oauth_token]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth1Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
2018-09-05 14:38:51.042 INFO 14888 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/connect/{providerId}/{providerUserId}],methods=[DELETE]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.removeConnection(java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
2018-09-05 14:38:51.043 INFO 14888 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/connect/{providerId}],methods=[GET],params=}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth2Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
2018-09-05 14:38:51.076 INFO 14888 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-09-05 14:38:51.076 INFO 14888 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-09-05 14:38:51.136 INFO 14888 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-09-05 14:38:51.839 INFO 14888 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-09-05 14:38:51.914 INFO 14888 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-09-05 14:38:51.919 INFO 14888 --- [ main] hello.Application : Started Application in 6.684 seconds (JVM running for 10.542)

Open the URL - http://localhost:8080/

Here is the first page, click on Connect to Facebook button

1

after click it will ask to login to facebook, Enter username, password and click on login button

2

It will show page like below image - Connected to Facebook

3

Now click on here link. after clicking output is like below image, show authorize true and show the login person name.

4

To see live demo watch below video and you will get complete understanding

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

Facebook Login using Spring Social & Spring Boot

You can download sample application created by Spring developer – gs-accessing-facebook

Here is the code sample which they added to implement Facebook Login

pom.xml – need to add below dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.social</groupId>
    <artifactId>spring-social-facebook</artifactId>
</dependency>

application.properties

spring.social.facebook.appId=233668646673605
spring.social.facebook.appSecret=33b17e044ee6a4fa383f46ec6e28ea1d

HelloController.java

package hello;

import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.PagedList;
import org.springframework.social.facebook.api.Post;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/")
public class HelloController {

    private Facebook facebook;
    private ConnectionRepository connectionRepository;

    public HelloController(Facebook facebook, ConnectionRepository connectionRepository) {
        this.facebook = facebook;
        this.connectionRepository = connectionRepository;
    }

    @GetMapping
    public String helloFacebook(Model model) {
        if (connectionRepository.findPrimaryConnection(Facebook.class) == null) {
            return "redirect:/connect/facebook";
        }
        model.addAttribute("facebookProfile", facebook.userOperations().getUserProfile());
        PagedList<Post> feed = facebook.feedOperations().getFeed();
        model.addAttribute("feed", feed);
        return "hello";
    }
}

hello.html

<html>
	<head>
		<title>Hello Facebook</title>
	</head>
	<body>
		<h3>Hello, <span th:text="${facebookProfile.name}">Some User</span>!</h3>
		
		<h4>Here is your feed:</h4>
		
		
from wrote:

message text


</body> </html>

To see live demo watch below video –

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java