Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrate Facebook Authentication into Spring Security in FacebookApp

I have a working web application that uses username/password SpringSecurity configuration. Now I want to port it into a simple Facebook application. For some reason, I want to do authentication by using facebook access token returned, as well as keeping the username-password validator.

In details, I would check the user facebook access token for authentication, returned by:

https://graph.facebook.com/oauth/access_token?client_id=[my_api_key]&redirect_uri=[my_redirect_uri]&client_secret=[my_api_secret]&code=[code]

The user don't need to provide any username/password since they already logged in with facebook. But I would like to keep (username/password) spring security configuration so that the users can sign in in my original website.

Does SpringSecurity support this kind of authentication? If the answer is yes, I wonder how it can be done? Does I need to write custom authentication provider(s) to do it?

UPDATE: In the end, we have customize the way SpringSecurity authenticate, so that it accept access_token as a authentication parameter by extending UsernamePasswordAuthenticationFilter (declaring it as formLoginFilter)

like image 791
Hoàng Long Avatar asked Dec 10 '22 07:12

Hoàng Long


1 Answers

There's another project from Spring: Spring Social which is very useful.

It supports multiple social networks. I successfully used it to authenticate to Facebook. I then wrote a small function to log a Facebook user into my Spring Security context:

protected void authenticate(UserDTO user){
    SecurityContextHolder.getContext().getAuthentication();
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
    token.setDetails(new WebAuthenticationDetails(getRequest()));
    Authentication authentication = authenticationManager.authenticate(token);
    SecurityContextHolder.getContext().setAuthentication(authentication);
}

UserDTO needs to have a username and (generated) password attribute and needs to be saved in database so your user-service (from Spring security) can retrieve it.

like image 57
Bart Vangeneugden Avatar answered Dec 14 '22 22:12

Bart Vangeneugden