Anda di halaman 1dari 15

29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

(http://baeldung.com)

A Secondary Facebook
Login with Spring Social
(/datadog)
Last modi ed: March 16, 2018

by baeldung (http://www.baeldung.com/author/baeldung/)

Security (http://www.baeldung.com/category/security-2/)

I just announced the newSpring Security 5 modules (primarily focused on OAuth2) in the
course:

>> CHECK OUT LEARN SPRING SECURITY (/learn-spring-security-course#new-modules)

http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 1/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

1. Overview
In this tutorial, we’ll focus on adding a new Facebook login to an existing form-login app.

We’re going to be using the Spring Social support to interact with Facebook and keep things clean and simple.

2. Maven Con guration


First, we will need to add spring-social-facebook dependency to our pom.xml:
(/datadog)

1 <dependency>
2     <groupId>org.springframework.social</groupId>
3     <artifactId>spring-social-facebook</artifactId>
4 </dependency>

3. Security Con g – Just Form Login


Let’s rst start from the simple security con guration where we just have form-based authentication:

http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 2/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

1 @Configuration
2 @EnableWebSecurity
3 @ComponentScan(basePackages = { "org.baeldung.security" })
4 public class SecurityConfig extends WebSecurityConfigurerAdapter {
5  
6     @Autowired
7     private UserDetailsService userDetailsService;
8  
9     @Override
10     protected void configure(AuthenticationManagerBuilder auth)
11       throws Exception {
12         auth.userDetailsService(userDetailsService);
13     }
14  
15     @Override
16     protected void configure(HttpSecurity http) throws Exception {
17 (/datadog)
        http
18         .csrf().disable()
19         .authorizeRequests()
20         .antMatchers("/login*").permitAll()
21         .anyRequest().authenticated()
22         .and()
23         .formLogin().loginPage("/login").permitAll();
24     }
25 }

We’re not going to spend a lot of time on this con g – if you want to understand it better, have a look at the form
login article (/spring-security-login).

4. Security Con g – Adding Facebook


Now, let’s add a new way to authenticate into the system – driven by Facebook:

http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 3/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

1 public class SecurityConfig extends WebSecurityConfigurerAdapter {


2  
3     @Autowired
4     private ConnectionFactoryLocator connectionFactoryLocator;
5  
6     @Autowired
7     private UsersConnectionRepository usersConnectionRepository;
8  
9     @Autowired
10     private FacebookConnectionSignup facebookConnectionSignup;
11  
12     @Override
13     protected void configure(HttpSecurity http) throws Exception {
14         http
15         .authorizeRequests()
16         .antMatchers("/login*","/signin/**","/signup/**").permitAll()
17 (/datadog)
        ...
18     }
19  
20     @Bean
21     public ProviderSignInController providerSignInController() {
22         ((InMemoryUsersConnectionRepository) usersConnectionRepository)
23           .setConnectionSignUp(facebookConnectionSignup);
24          
25         return new ProviderSignInController(
26           connectionFactoryLocator,
27           usersConnectionRepository,
28           new FacebookSignInAdapter());
29     }
30 }

Let’s carefully look at the new con g:


we’re using a ProviderSignInController to enable the Facebook authentication
by sending a POST to “/signin/facebook” – this controller will initiate a user sign-in using the Facebook
service provider
http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 4/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

we’re setting up a SignInAdapter to handle the login logic in our application


and we also setting up a ConnectionSignUp to handle signing up users implicitly when they rst authenticate
with Facebook

5. The Sign-In Adapter


Get access to
Simply put, this adapter is a bridge between the controller above – driving the Facebook user sign-in ow – and
the Video
our speci c local application:
Security basics for a REST API
1 public class FacebookSignInAdapter implements SignInAdapter {
2     @Override
3 Email
    public AddresssignIn(
String
4 (/datadog)
      String localUserId,
5       Connection<?> connection,
6       NativeWebRequest request) {
Get Access
7          
8         SecurityContextHolder.getContext().setAuthentication(
9           new UsernamePasswordAuthenticationToken(
10           connection.getDisplayName(), null,
11           Arrays.asList(new SimpleGrantedAuthority("FACEBOOK_USER"))));
12          
13         return null;
14     }
15 }

Note that users logged-in using Facebook will have role FACEBOOK_USER, while users logged in using form will
have role USER.

6. Connection Sign Up
http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 5/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

When a user authenticates with Facebook for the rst time, they have no existing account in our application.
This is the point where we need to create that account automatically for them; we’re going to be using
a ConnectionSignUp to drive that user creation logic:

1 @Service
2 public class FacebookConnectionSignup implements ConnectionSignUp {
3  
4     @Autowired
5     private UserRepository userRepository;
6  
7     @Override
8     public String execute(Connection<?> connection) {
9         User user = new User();
10         user.setUsername(connection.getDisplayName());
11         user.setPassword(randomAlphabetic(8));
12
(/datadog)
        userRepository.save(user);
13         return user.getUsername();
14     }
15 }

As you can see, we created an account for the new user – using their DisplayName as username.

7. The Facebook Properties


Next, let’s con gure Facebook properties in our application.properties:

1 spring.social.facebook.appId=YOUR_APP_ID
2 spring.social.facebook.appSecret=YOUR_APP_SECRET

Note that:

http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 6/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

We need to create a Facebook application to obtain appId and appSecret


From Facebook application Settings, make sure to Add Platform “Website” and http://localhost:8080/ is the
“Site URL”

8. The Front End


Finally, let’s take a look at our front end.
We’re going to now have support for these two authentication ows – form login and Facebook – on our login
page:

1 <html>
2 <body>
(/datadog)
3 <div th:if="${param.logout}">You have been logged out</div>
4 <div th:if="${param.error}">There was an error, please try again</div>
5  
6 <form th:action="@{/login}" method="POST" >
7     <input type="text" name="username" />
8     <input type="password" name="password" />
9     <input type="submit" value="Login" />
10 </form>
11      
12 <form action="/signin/facebook" method="POST">
13     <input type="hidden" name="scope" value="public_profile" />
14     <input type="submit" value="Login using Facebook"/>
15 </form>
16 </body>
17 </html>

Finally – here’s the index.html:

http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 7/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

1 <html>
2 <body>
3 <nav>
4     <p sec:authentication="name">Username</p>      
5     <a th:href="@{/logout}">Logout</a>                    
6 </nav>
7  
8 <h1>Welcome, <span sec:authentication="name">Username</span></h1>
9 <p sec:authentication="authorities">User authorities</p>
10 </body>
11 </html>

Note how this index page is displaying usernames and authorities.


And that’s it – we now have two ways to authenticate into the application.
(/datadog)

9. Conclusion
In this quick article we learned how to use spring-social-facebook to implement a secondary authentication ow
for our application.
And of course, as always, the source code is fully available over on GitHub
(https://github.com/eugenp/tutorials/tree/master/spring-social-login).

I just announced the new Spring Security 5 modules (primarily focused on


OAuth2) in the course:

>> CHECK OUT LEARN SPRING SECURITY (/learn-spring-security-course#new-modules)


http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 8/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

(/datadog)

Learn the basics of securing a REST API with Spring

Get access to the video lesson!

http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 9/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

Your Email

Access >>

  Subscribe    newest  oldest  most voted

(/datadog)
Hinotori  

Thanks! Very good article!


Guest
 1    1 year ago 

Eugen Paraschiv (http://www.baeldung.com/)  

Glad you liked it. Cheers,


Guest
Eugen.

 2    1 year ago

Brandon Vulaj  

I’m integrating this into an application using spring session (redis) and csrf – should this con guration work as expected still?
Guest
 1    1 year ago 

http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 10/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

Eugen Paraschiv (http://www.baeldung.com/)  

Hey Brandon,
Guest
Theoretically – yes. Spring Session shouldn’t have an impact, and CSRF is something you’ll of course need to make
sure your front-end handles, but as long as that’s the case – you should be good to go.

That being said, whenever you get part of a working project and move it to another project – there are always things
you may need to tweak – as I’m sure you know. So, keep that in mind when you move the logic over.

Cheers and best of luck with the implementation,


Eugen.

 2    1 year ago 

Brandon Vulaj  

(/datadog)
Guest
@baeldung:disqus – Have you seen the social providers not matching the `state` param? The request goes out
with the proper state param, and the request comes back with the proper state param, however, the check in
verifyStateParameter always sees originalState on the Session as null. Could this be an integration issue with
Spring Session?

 1    1 year ago 

Eugen Paraschiv (http://www.baeldung.com/)  

Hey @brandonvulaj:disqus – I haven’t seen that exact behavior no – but keep in mind a couple of important notes.
Guest
First – some of the social providers don’t 100% adhere to the spec. It’s a bit unfortunate but that is sometimes the
case. Second – the implementation is not set in stone, and – if a change did occur – the library may need to catch
up. So, in cases like this, you’ll need to debug your way through whatever is happening – and of course have a
good understanding of what “should” be happening rst. Hope that points you… Read more »

 1    1 year ago

Kingsley  

http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 11/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

Guest
Thanks for this very good article. How can one integrate other social logins like Twitter, Google and Linked into this sample you
provided?

 1    11 months ago 

Eugen Paraschiv (http://www.baeldung.com/)  

Well, at a high level – you need to use the associated Spring Social project – there are solutions for Twitter, Google,
Guest
etc. There might be some implementation details that vary, but that’s the general direction to go in.

 1    11 months ago 

Kingsley  

(/datadog) Thank you so much for your kind response.


Guest

 1    11 months ago

Robert Vangor  

Great article, you really helped me !


Guest Can I use Spring Social Google community project as well ? Is it outdated or will it work ne even with spring boot ?

 1    10 months ago 

Eugen Paraschiv (http://www.baeldung.com/)  

Hey Robert, I’m glad the material was helpful. I could add that to the Content Calendar of the site, sure – but it should
Guest
actually be relatively similar.
Cheers,
Eugen.

 0    10 months ago

http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 12/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

(/datadog)

http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 13/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

CATEGORIES

SPRING (HTTP://WWW.BAELDUNG.COM/CATEGORY/SPRING/)

(/datadog)
REST (HTTP://WWW.BAELDUNG.COM/CATEGORY/REST/)
JAVA (HTTP://WWW.BAELDUNG.COM/CATEGORY/JAVA/)
SECURITY (HTTP://WWW.BAELDUNG.COM/CATEGORY/SECURITY-2/)
PERSISTENCE (HTTP://WWW.BAELDUNG.COM/CATEGORY/PERSISTENCE/)
JACKSON (HTTP://WWW.BAELDUNG.COM/CATEGORY/JACKSON/)
HTTPCLIENT (HTTP://WWW.BAELDUNG.COM/CATEGORY/HTTP/)
KOTLIN (HTTP://WWW.BAELDUNG.COM/CATEGORY/KOTLIN/)

SERIES

JAVA “BACK TO BASICS” TUTORIAL (HTTP://WWW.BAELDUNG.COM/JAVA-TUTORIAL)


JACKSON JSON TUTORIAL (HTTP://WWW.BAELDUNG.COM/JACKSON)
HTTPCLIENT 4 TUTORIAL (HTTP://WWW.BAELDUNG.COM/HTTPCLIENT-GUIDE)
REST WITH SPRING TUTORIAL (HTTP://WWW.BAELDUNG.COM/REST-WITH-SPRING-SERIES/)
SPRING PERSISTENCE TUTORIAL (HTTP://WWW.BAELDUNG.COM/PERSISTENCE-WITH-SPRING-SERIES/)
SECURITY WITH SPRING (HTTP://WWW.BAELDUNG.COM/SECURITY-SPRING)

ABOUT

http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 14/15
29/03/2018 A Secondary Facebook Login with Spring Social | Baeldung

ABOUT BAELDUNG (HTTP://WWW.BAELDUNG.COM/ABOUT/)


THE COURSES (HTTP://COURSES.BAELDUNG.COM)
CONSULTING WORK (HTTP://WWW.BAELDUNG.COM/CONSULTING)
META BAELDUNG (HTTP://META.BAELDUNG.COM/)
THE FULL ARCHIVE (HTTP://WWW.BAELDUNG.COM/FULL_ARCHIVE)
WRITE FOR BAELDUNG (HTTP://WWW.BAELDUNG.COM/CONTRIBUTION-GUIDELINES)
CONTACT (HTTP://WWW.BAELDUNG.COM/CONTACT)
COMPANY INFO (HTTP://WWW.BAELDUNG.COM/BAELDUNG-COMPANY-INFO)
TERMS OF SERVICE (HTTP://WWW.BAELDUNG.COM/TERMS-OF-SERVICE)
PRIVACY POLICY (HTTP://WWW.BAELDUNG.COM/PRIVACY-POLICY)
EDITORS (HTTP://WWW.BAELDUNG.COM/EDITORS)
MEDIA KIT (PDF) (HTTPS://S3.AMAZONAWS.COM/BAELDUNG.COM/BAELDUNG+-+MEDIA+KIT.PDF)

(/datadog)

http://www.baeldung.com/facebook-authentication-with-spring-security-and-social 15/15

Anda mungkin juga menyukai