使用 Firebase 进行 Spring Boot 和 vueJs 身份验证

2024-01-03

我正在尝试在后端实现身份验证 spring boot 并在前端实现 vue Js,问题是我已将后端只读连接到数据库,因此使用 vue js 进行身份验证Firebase 身份验证 https://firebase.google.com/products/auth/特征。

问题是我的端点仍然可以访问,任何人都可以使用邮递员发送请求和获取数据 !

如果有人知道如何解决这个问题,请继续,谢谢!

PS:我不认为我可以提供帮助,但无论如何这是我的登录代码,@Renaud Tarnec

import firebase from 'firebase'

export default {
  name: 'login',
  data: function() {
    return {
      email: '',
      password: ''
    }
  },
  methods: {
    signIn: function() {
      firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(
        function(user) {
          alert('You are connected')
        },
        function(err) {
          aler('Ooops,' + err.message)
        }
      );
    }
  }
}
</script>

例如,这是我的存储库的一部分,其中有事件列表:

@RequestMapping("api/events")
public class EventController {
    @Autowired
    private EventRepository eventrepository;

    @GetMapping
    public ArrayList<Event> find() {
        ArrayList<Event> events = new ArrayList<Event>();
        for (Event e : eventrepository.findAll()) {
            System.out.println(e);
            events.add(e);
        }
        return events;
    }

这是正常行为,因为您使用 admin sdk 凭据向 firestore 发送请求。

您需要在 Spring Boot 应用程序中添加一些身份验证。

我将一些代码放在一起,将您的所有请求置于 firebase 身份验证之后。

FirebaseConfig.java

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix="firebase")
public class FirebaseConfig {

    private static final Logger logger = LoggerFactory.getLogger(FirebaseConfig.class);

    private String databaseURL;
    private String serviceAccount;

    @Bean
    public DatabaseReference firebaseDatabse() {
        DatabaseReference firebase = FirebaseDatabase.getInstance().getReference();
        return firebase;
    }

    @PostConstruct
    public void init() {

        try {
            FirebaseApp.getInstance();
        } catch (IllegalStateException e) {
            try {
                InputStream inputStream = FirebaseConfig.class.getClassLoader().getResourceAsStream(serviceAccount);

                try {
                    FirebaseOptions options = new FirebaseOptions.Builder().setCredentials(GoogleCredentials.fromStream(inputStream))
                            .setDatabaseUrl(databaseURL).build();

                    FirebaseApp.initializeApp(options);
                } catch (IOException ioE) {
                    ioE.printStackTrace();
                }
            } catch (NullPointerException nullE) {
                nullE.printStackTrace();
            }
        }

    }

    public String getDatabaseURL() {
        return databaseURL;
    }

    public void setDatabaseURL(String databaseURL) {
        this.databaseURL = databaseURL;
    }

    public String getServiceAccount() {
        return serviceAccount;
    }

    public void setServiceAccount(String serviceAccount) {
        this.serviceAccount = serviceAccount;
    }
}

然后您需要启用网络安全:

WebSecurityConfig.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(WebSecurityConfiguration.class);

    /**
     * Use to create instance of {@link FirebaseAuthenticationTokenFilter}.
     *
     * @return instance of {@link FirebaseAuthenticationTokenFilter}
     */
    public FirebaseAuthenticationTokenFilter firebaseAuthenticationFilterBean() throws Exception {
        logger.debug(
                "firebaseAuthenticationFilterBean():: creating instance of FirebaseAuthenticationFilter.");

        FirebaseAuthenticationTokenFilter authenticationTokenFilter = new FirebaseAuthenticationTokenFilter();

        return authenticationTokenFilter;
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity
                .cors()
                .and()
                .csrf()
                .disable()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Custom security filter
        httpSecurity.addFilterBefore(firebaseAuthenticationFilterBean(),
                UsernamePasswordAuthenticationFilter.class);
    }

}

最后,您添加一个请求过滤器,用于在每次针对 api 发出请求时验证访问令牌。

FirebaseAuthenticationTokenFilter.java

@Component
public class FirebaseAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(FirebaseAuthenticationTokenFilter.class);
    private final static String TOKEN_HEADER = "Authorization";

    /**
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        logger.debug("doFilter:: authenticating...");

        HttpServletRequest httpRequest = request;
        String authToken = httpRequest.getHeader(TOKEN_HEADER);

        if (Strings.isNullOrEmpty(authToken)) {
            filterChain.doFilter(request, response);
            return;
        }

        try {
            Authentication authentication = getAndValidateAuthentication(authToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            logger.debug("doFilter():: successfully authenticated.");
        } catch (Exception ex) {
            HttpServletResponse httpResponse = response;
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            logger.debug("Fail to authenticate.", ex);
        }

        filterChain.doFilter(request, response);
    }

    /**
     *
     * @param authToken Firebase access token string
     * @return the computed result
     * @throws Exception
     */
    private Authentication getAndValidateAuthentication(String authToken) throws Exception {
        Authentication authentication;

        FirebaseToken firebaseToken = authenticateFirebaseToken(authToken);
        authentication = new UsernamePasswordAuthenticationToken(firebaseToken, authToken, new ArrayList<>());

        return authentication;
    }

    /**
     * @param authToken Firebase access token string
     * @return the computed result
     * @throws Exception
     */
    private FirebaseToken authenticateFirebaseToken(String authToken) throws Exception {
        ApiFuture<FirebaseToken> app = FirebaseAuth.getInstance().verifyIdTokenAsync(authToken);

        return app.get();
    }

    @Override
    public void destroy() {
        logger.debug("destroy():: invoke");
    }

}

现在,您的 API 端点将针对未经授权的请求进行保存。

在您的 Web 应用程序中,您可以像平常一样使用 firebase 处理授权。在对 spring-boot 应用程序的每个请求中,您将访问令牌传递为Authorization header.

请记住,这并不是真正的保存,因为 Spring Boot API 充当 Firebase SDK 的管理员。

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

使用 Firebase 进行 Spring Boot 和 vueJs 身份验证 的相关文章

随机推荐

  • 这个语法在 Javascript 中的含义是什么

    我正在 javascript 中寻找 TWILIO 的 API 我发现了类似的东西 const connect createLocalTracks Twilio Video navigator mediaDevices enumerateD
  • 没有异常处理的力量?

    在 Eclipse 中进行 Java 编程 我习惯于处理异常 在使用 VisualStudio 的 C 中 似乎我不能在方法上说 抛出异常 经过大量编码后 我发现了很多异常 并且必须在测试过程中发现它们时捕获它们 我想被迫处理它们 以便 V
  • 如何对 foreach 循环中迭代的元素进行分段

    我需要循环遍历整个用户列表 但需要一次获取 20 个 foreach var student in Class Students Take 20 Console WriteLine You belong to Group groupNumb
  • 无法自动装配方法

    我收到这个错误 org springframework beans factory BeanCreationException Could not autowire method 这是我的spring的xml配置
  • UIPickerView Swift 上奇怪的自定义背景颜色

    将自定义 UIColor 分配给 UIPickerViews 的背景时 我得到了奇怪的颜色 我为 textViews 和 pickerViews 创建了颜色 如下所示 let myTextViewBackgroundColor UIColo
  • 当node.js宕机时,如何让它自动恢复?

    由于节点基本上是一个进程 因此当出现严重错误时 整个应用程序就会崩溃 我现在有几个基于 Express 构建的应用程序 并且我正在使用一些手动方法来防止延长停机时间 process on uncaughtException 和自定义心跳监视
  • Mysql find_in_set 斜杠( / ) 分隔符

    我的值为 1 2 3 4 5 2 3 6 我想找到值 2 所以结果必须是 1 2 2 3 6 我不想使用 LIKE 运算符 有没有办法在FIND IN SET函数中设置分隔符 您可以使用like or find in set 这是一种方法
  • 如何编写 javascript 来重新排序 pdf 文档的页面?

    我有一个双面文档作为两个单独的 pdf 文件 一个文档的正面页面和第二个文档的背面页面 front pdf rear pdf 我还将它们合并为一个包含所有页面的文档 但所有正面页面都在背面页面之前 页面排序的形式为 1 3 5 7 n 2
  • Spring 启动和 SQLite

    我正在尝试将 SQLite 与 Spring Boot 应用程序一起使用 我知道 Spring Boot 对 MongoDB 等提供了出色的支持 但我找不到将 Spring Boot 与 SQLite 结合使用的方法 有什么建议从哪里或如何
  • android中的sqlite示例程序[关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我是数据库概念的新手 特别是我需要相关的数据库概念 我想要一个在 android 上使用 sqlite 数据库的示例 我浏览了 andro
  • 替换php数组中的所有键

    这是我的数组 apple some code beta other code cat other code 2 如何将所有 e 字母替换为 在键名称中并保留值 这样我就会得到类似的东西 appl some code b ta other c
  • 当我尝试添加文本剪辑时,出现有关 ImageMagick With Python/MoviePy 的错误

    我正在使用 python 3 8 5 以及最新版本的 imagemagick 和 moviepy 错误 与代码 Traceback most recent call last File C Users edgib102 AppData Lo
  • JVM 内存使用失控

    我有一个 Tomcat Web 应用程序 它代表客户端执行一些内存和 CPU 密集型任务 这是正常现象 也是所需的功能 然而 当我运行 Tomcat 时 内存使用量会随着时间的推移飙升至 4 0GB 以上 此时我通常会终止该进程 因为它会扰
  • 为什么 Clojure 变量 arity args 根据使用而获得不同的类型?

    在回答中另一个问题 https stackoverflow com questions 26039461 does clojure have the c sharp equivalent of yield 26040454 comment4
  • 在 Windows 10 中使用 PS 将程序固定到开始菜单

    我正在尝试将程序固定到 Windows 10 中的开始菜单 shell New Object ComObject Shell Application Folder shell NameSpace C Test exe Folder Pars
  • Firestore 查询子集合

    我以为我读到您可以使用新的 Firebase Firestore 查询子集合 但我没有看到任何示例 例如 我通过以下方式设置 Firestore Dances collection 舞蹈名称 Songs collection songNam
  • Twitter 流媒体的 Kafka Consumer 弃用错误

    我一直在研究 Kafka Twitter 流式提要数据 我正在关注以下链接中的示例 http www hahaskills com tutorials kafka Twitter doc html http www hahaskills c
  • 小牛上的 opencv for python

    我知道现在还为时过早 但我已经升级到 OSX mavericks 并且无法使用 Homebrew 安装 opencv gt Installing dependencies for opencv cmake pkg config libpng
  • 如何用 C 语言编写“如果 x 等于 5 或​​ 4 或 78 或...”

    我有一个关于在 if 语句中使用逻辑运算符的快速问题 目前我有一个 if 语句检查 x 是否等于 5 或 4 或 78 if x 5 x 4 x 78 blah 我想知道我是否可以将所有这些浓缩为 if x 5 4 78 blah 不好意思
  • 使用 Firebase 进行 Spring Boot 和 vueJs 身份验证

    我正在尝试在后端实现身份验证 spring boot 并在前端实现 vue Js 问题是我已将后端只读连接到数据库 因此使用 vue js 进行身份验证Firebase 身份验证 https firebase google com prod