将Spring Security与Facebook登录集成

时间:2014-05-03 04:10:28

标签: facebook-graph-api spring-mvc spring-security spring-social spring-social-facebook

我为我的项目使用Spring MVC和Spring Security ..这使用我自己的用户数据进行身份验证。但现在我试图与Facebook整合。我已经在Facebook上创建了应用程序,这意味着我获得了客户端ID和客户端密码。我还在SO和一些文档中阅读了一些问题,但仍然卡住...

我创建控制器以登录Facebook:

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/login/")
public class LoginController {

    String fb_app_id="my_client_id";
    String redirect_url="localhost:8888";
    String state="public_profile,email,user_friends";
    String key="my_client_secret";

    @RequestMapping("/facebook")
    public String login( ModelMap model) {

        String url="https://www.facebook.com/dialog/oauth/?"
                   + "client_id=" + fb_app_id
                   + "&redirect_uri=" + redirect_url
                   + "&scope=email,publish_stream,user_about_me,friends_about_me"
                   + "&state=" + key
                   + "&display=page"
                   + "&response_type=code";
        return "redirect:"+url;

    }

}

我认为它有效,因为当我尝试连接时,我可以使用下面的Javascript显示我的名字:

function testAPI() {
  console.log('Welcome!  Fetching your information.... ');
  FB.api('/me', function(response) {
    console.log('Good to see you, ' + response.name + '.');
    document.getElementById('status').innerHTML = 'Good to see you, ' +
      response.name;
  });
}

但我仍然混淆了如何将其与Spring Security集成。如果有人有任何例子我会很感激...

这是我的spring-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <http pattern="/common/*" security="none" />

    <http auto-config="true">
        <intercept-url pattern="/maintenance/*" access="ROLE_USER" />
        <intercept-url pattern="/_ah/*" access="ROLE_USER" />
        <intercept-url pattern="/predict/*" access="ROLE_USER" />

        <form-login login-page='/' default-target-url='/predict/list'
            login-processing-url="/login_check" authentication-failure-url="/index?login_error=2"
            always-use-default-target="true" />
        <logout logout-url="/logout" logout-success-url="/index" />
    <!--    <custom-filter ref="socialAuthenticationFilter" before="PRE_AUTH_FILTER" /> -->
    <!--    <custom-filter before="FORM_LOGIN_FILTER"
            ref="facebookAuthenticationFilter" /> -->
    </http>

    <authentication-manager>
        <authentication-provider ref="gaeAuthenticationProvider" />
    <!--    <authentication-provider ref="authenticationProviderFacebook"> 
        </authentication-provider>-->
    </authentication-manager>

    <beans:bean id="gaeAuthenticationProvider"
        class="com.games.predictor.security.AuthenticationProvider" />

</beans:beans>  

我有自己的类使用JPA对userdata进行身份验证...

package com.games.predictor.security;

import java.util.List;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import com.games.predictor.UserDAO;


public class AuthenticationProvider extends AbstractUserDetailsAuthenticationProvider
{
    //private SecurityDao securityDao; 

    @Override
    protected UserDetails retrieveUser(String username,
            UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException
    {
        final String password = authentication.getCredentials().toString();
        System.out.println(username+"===="+password);
        //This line for validating user with database
        boolean isValidUser = UserDAO.INSTANCE.isValidUser(username, password);
        if (isValidUser)
        {
            final List<SimpleGrantedAuthority> authorities = UserDAO.INSTANCE.getAuthoritiesByUser(username);
            //User u=new User(username,password,);
            return new User(username, password, true, true, true, true, authorities);
        }
        else
        {
            authentication.setAuthenticated(false);
            throw new BadCredentialsException("Username/Password does not match for " 
                + authentication.getPrincipal());
        }

    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails arg0,
            UsernamePasswordAuthenticationToken arg1)
            throws AuthenticationException {
        // TODO Auto-generated method stub

    }
}

我在最近几天做了一些研究,但仍然坚持下去。

我的项目堆栈:Java,Spring MVC,Spring Security,Google App Engine,Google Data Store,JPA。 (春季社交核心和春季社交Facebook添加)

2 个答案:

答案 0 :(得分:2)

丹尼尔,请你详细说明你在哪里陷入困境。我使用相同的堆栈来整合facebook登录。但我没有使用Spring Social。我相信这不是必需的。

将Facebook登录信息与现有登录信息集成的步骤。

  1. 使用jsp中的facebook javascript plugin登录facebook。
  2. 用户批准您的应用后。 OAuth使用图表API获取客户端的电子邮件ID,生成身份验证令牌。
  3. 使用Ajax将电子邮件ID发送到服务器。
  4. 将发送到服务器端的电子邮件ID与数据库中的电子邮件ID进行比较。
  5. 如果电子邮件ID相同,请登录用户。
  6. 身份验证令牌是临时的,因此我发现将其发送到服务器端或保存在db中毫无意义。它在本地保存在客户端。并且fb javascript插件可以处理它。通过这种方式,它可以帮助您省去实施spring social facebook的麻烦。

    我看到你正在使用控制器进行facebook登录,这不是必需的,相信我使用fb javascript插件非常简单&amp;容易。

答案 1 :(得分:2)

我认为你不应该手动处理Facebook。您可以使用一个非常简单的库:https://github.com/pac4j/spring-security-pac4j来验证OAuth(Facebook,Twitter,Google ...),CAS,SAML,OpenID(连接)和GAE。请参阅演示:https://github.com/pac4j/spring-security-pac4j-demo