将 Spring Security 与 Facebook 登录集成

2023-12-27

我在我的项目中使用 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 对用户数据进行身份验证...

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 https://github.com/pac4j/spring-security-pac4j对 OAuth(Facebook、Twitter、Google...)、CAS、SAML、OpenID (Connect) 和 GAE 进行身份验证。看演示:https://github.com/pac4j/spring-security-pac4j-demo https://github.com/pac4j/spring-security-pac4j-demo

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 Spring Security 与 Facebook 登录集成 的相关文章

随机推荐

  • 了解何时使用有状态服务以及何时依赖 Azure Service Fabric 中的外部持久性

    我花了很多晚上的时间评估 Azure Service Fabric 作为我们当前 WebApps CloudServices 堆栈的替代品 并且有点不确定如何决定何时具有状态的服务 参与者应该是有状态参与者 以及何时应该是无状态参与者外部持
  • JUnit4 是否开始支持测试排序?是故意的吗?

    JUnit 实际上是 JUnit 4 的新手 遇到了执行测试的套件方法 RunWith Suite class Suite SuiteClasses CreateNewProfile class EditProfile class publ
  • 该命令返回一个非零代码:127

    我正在尝试构建下面的 Dockerfile 但它一直失败RUN ocp indent help saying ocp indent not found The command bin sh c ocp indent help returne
  • 在 iPhone 中裁剪星形图像

    我有一个矩形图像 但我想在我的 iPhone 应用程序中将此图像裁剪为星形 那么请问有人可以建议我如何做到这一点吗 请建议 谢谢 See the 对相关问题发表评论 https stackoverflow com questions 262
  • 如何使用派生列转换将字符串 (YYMMDD) 转换为日期时间?

    我有一个输入文本文件 其中包含几列 即TransactionID receiveddt description等等 recieveddt列具有以下格式的日期值120419 yymmdd 我想将 txt 输入文件加载到数据库中 但目标列rec
  • 有没有java api可以访问bugzilla? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 是否有一个 独立的 java api 将 XML RPC 接口包装到 bugzilla 我不想为它编写
  • Magento - 在所有页面中创建固定块

    如何在不点击模块名称的情况下在包括主页在内的所有页面中可见的右列中创建一个块 谢谢 希望能很好地理解你的问题 1 创建一个模块 例如Mynamespace Mymodule 2 在模块中创建一个块 例如 Mynamespace Mymodu
  • Spock Test,只检查方法是否被调用,不执行

    在我们的 Spock 测试中 我们想要检查我们的软件中是否选择了正确的路径 但我们不想测试所调用方法的功能 这是在单独的测试中完成的 def Test setup service metaClass innerMethod gt retur
  • SSIS 任务导入不一致的列数?

    问题 我经常收到来自不同供应商的提要文件 尽管列名称一致 但当某些供应商发送源文件中包含或多或少列的文本文件时 就会出现问题 此外 这些文件的排列不一致 除了 Cozy Roc 提供的动态数据流任务之外 还有另一种方法可以导入这些文件 我不
  • 如何使用 Mockito 模拟 void 方法

    如何模拟具有 void 返回类型的方法 我实现了一个观察者模式 但我无法用 Mockito 模拟它 因为我不知道如何做 我试图在互联网上找到一个例子 但没有成功 我的班级是这样的 public class World List
  • 我什么时候应该在 UML 图中使用依赖关键字 <>?

    参考这个来源 https www uml diagrams org dependency html UML的定义是 依赖性是一种有向关系 用于表明某个 UML 元素或一组元素需要 需要或依赖于其他模型元素来进行规范或实现 但后来根据教科书的
  • 如何在android中的gridview布局中添加页脚

    我需要在 android 中的 gridview 布局中添加某种页脚视图 没有我可以找到的官方文档 而且我无法找到在我的谷歌搜索中实际有效的方法 有人取得了任何成就吗 像这样 我需要制作一个显示在 gridview 底部的按钮 以便我可以在
  • scrapy“请求网址中缺少方案”

    下面是我的代码 import scrapy from scrapy http import Request class lyricsFetch scrapy Spider name lyricsFetch allowed domains m
  • WCF 给出不安全或不正确安全的故障错误

    我正在尝试使用远程 svc Web 服务 我使用创建代理类svcutil exe 之后我将该类添加到我的控制台应用程序中 但它产生了一个错误 从另一方收到不安全的错误或不正确的安全故障 故障代码及详细信息请参见内部故障异常 System S
  • 使用 Echo 测试 POST 请求(预期输出与实际输出)

    我对 Go 有点陌生 所以 如果这是一个愚蠢的问题 我很抱歉 我最近一直在尝试使用 Echo 的一些 API 我正在尝试测试 Go echo 的路由 POST 处理程序 它获取 json 并将其放入数组中 以下是处理程序的代码main go
  • 如何将 Vagrant 项目目录与现有 VirtualBox 虚拟机关联?

    不知何故 我的 Vagrant 项目已与其 VirtualBox VM 解除关联 因此当我vagrant upVagrant 将导入基础盒子并创建一个新的虚拟机 有没有办法将 Vagrant 项目与现有 VM 重新关联 Vagrant 如何
  • 如何在Python中更改图像捕获日期?

    由于相机日期设置错误 我有超过 500 张图像 png jpg 的拍摄日期 拍摄日期 错误 我将照片移至移动设备 移动图库根据 拍摄日期 对照片进行排序 我希望所有照片都按顺序显示 那么如何使用 python 脚本更改捕获日期 拍摄日期 使
  • npm package.json 别名,如 webpack

    我正在尝试为模块添加别名 但是我不确定如何使用 package json 来做到这一点 在 webpack 中你会做这样的事情 module exports resolve alias pixi js pixi js legacy 但是没有
  • Spring Data JPA 通过嵌入对象属性查找

    我想编写一个 Spring Data JPA 存储库接口方法签名 它可以让我找到具有该实体中嵌入对象的属性的实体 有谁知道这是否可能 如果可能的话如何 这是我的代码 Entity Table name BOOK UPDATE QUEUE i
  • 将 Spring Security 与 Facebook 登录集成

    我在我的项目中使用 Spring MVC 和 Spring Security 这使用我自己的用户数据进行身份验证 但现在我正在尝试与 Facebook 整合 我已经在 Facebook 上创建了应用程序 这意味着我获得了客户端 ID 和客户