facebook-graph-api - 将 Spring Security 与 Facebook 登录集成

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

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

我创建 Controller 以使用 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 对用户数据进行身份验证...

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。 (添加了 Spring Social Core 和 Spring Social Facebook)

最佳答案

我认为您不应该手动处理 Facebook。您可以创建一个非常简单的库:https://github.com/pac4j/spring-security-pac4j对 OAuth(Facebook、Twitter、Google...)、CAS、SAML、OpenID (Connect) 和 GAE 进行身份验证。查看演示:https://github.com/pac4j/spring-security-pac4j-demo

关于facebook-graph-api - 将 Spring Security 与 Facebook 登录集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23440141/

相关文章:

javascript - Facebook 将自定义操作发布到时间线

java - StandardReflectionParameterNameDiscoverer 如何编译到 jdk 版本 50?

c# - 在 facebook ads api 中获取图像的哈希码

spring - 具有可选属性的请求正文

java - DataForm 发布值但在服务器上为空

Spring Boot 和 Spring Security 过滤器未过滤正确的请求

java - 添加了 Spring Security,现在我得到 "No WebApplicationContext found: no ContextLoaderListener registered?"

java - 升级到4.2.3版本时Spring上下文初始化失败

javascript - 网站缩略图无法在 Facebook 上使用?

java - Facebook 登录 :Can't Load URL The domain of this URL isn't included in the app's domains