首页 Java java教程 Spring Boot 中的 OAuth 身份验证:Google 和 GitHub 登录集成指南

Spring Boot 中的 OAuth 身份验证:Google 和 GitHub 登录集成指南

Aug 31, 2024 pm 06:31 PM

使用 OAuth 2.0 增强安全性:在 Spring Boot 中实现社交登录

在现代 Web 开发的世界中,保护您的应用程序并使用户的身份验证尽可能顺利是首要任务。这就是 OAuth 2.0 的用武之地——它是一个强大的工具,不仅可以帮助保护您的 API,还可以让用户使用现有帐户从 Google 和 GitHub 等平台登录。这使每个人的事情变得更容易:用户不需要记住另一个密码,开发人员可以获得可靠的方法来管理身份验证。

在本博客中,我将逐步引导您了解如何在 Spring Boot 应用程序中设置 OAuth 2.0。我们将集成 Google 和 GitHub 进行身份验证,以便您的用户可以选择他们想要使用哪个服务来登录。我还将向您展示如何使用 JWT(JSON Web 令牌)保护您的 API 端点,确保仅经过身份验证的用户可以访问他们应该访问的资源。

无论您是构建新应用程序还是为现有应用程序添加安全性,本指南都将为您提供保持 Spring Boot 应用程序安全和用户友好所需的工具。

访问 https://start.spring.io/

创建项目

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

下载 zip 并解压,然后将项目加载到您的 IDE。

Spring Boot 中的“OAuth2 Client”依赖项简化了 OAuth 2.0 身份验证与 Google 和 GitHub 等提供商的集成。它处理整个 OAuth 登录流程,包括将用户重定向到提供商的登录页面、管理令牌和保护 API 端点。通过添加此依赖项,您可以轻松地在 Spring Boot 应用程序中启用安全且用户友好的身份验证。

Spring Boot 中的“Spring Web”依赖对于开发 Web 应用程序至关重要。它提供了一些基本功能,例如 RESTful API 创建、MVC 架构支持以及提供 HTML 视图的能力。使用 Spring Web,您可以轻松处理 HTTP 请求和响应、管理路由以及与其他 Spring 组件集成,使其成为构建健壮的 Web 应用程序的基础部分。

应用程序配置

要设置 Spring Boot 应用程序以通过 Google 和 GitHub 进行 OAuth 2.0 身份验证,您需要配置 application.properties 文件。此文件包含应用程序的基本设置,包括 OAuth 客户端凭据、日志记录级别和 JWT 配置。

spring.application.name=oauth2-authentication-service
server.port=8000

#for google
spring.security.oauth2.client.registration.google.client-id=YOUR_GOOGLE_CLIENT_ID
spring.security.oauth2.client.registration.google.client-secret=YOUR_GOOGLE_CLIENT_SECRET

#for github
spring.security.oauth2.client.registration.github.client-id=YOUR_GITHUB_CLIENT_ID
spring.security.oauth2.client.registration.github.client-secret= YOUR_GITHUB_CLIENT_SECRET

OAuth 客户端配置: 将 YOUR_GOOGLE_CLIENT_ID、YOUR_GOOGLE_CLIENT_SECRET、YOUR_GITHUB_CLIENT_ID 和 YOUR_GITHUB_CLIENT_SECRET 替换为您在注册应用程序时从 Google 和 GitHub 获取的凭据。

要向 Google 和 GitHub 注册您的应用程序以进行 OAuth 2.0 身份验证,我们需要访问 https://console.cloud.google.com

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

点击 API 服务

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

凭证 ->创建凭证 -> OAuth 客户端 ID

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

OAuth 客户端 ID ->创建 OAuth 客户端 ID

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

选择应用程序类型网络应用程序

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

给出应用程序名称

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

使用此 URL 设置 授权重定向 URI,这里我们的应用程序在 8000 端口上运行,因此应用程序端口为 8000。然后单击创建

http://localhost:8000/login/oauth2/code/google

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

创建 OAuth 客户端后,我们会获取客户端 ID 和客户端密钥。

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

copy both and replace with the the properties of application.properties file

spring.security.oauth2.client.registration.google.client-id=YOUR_GOOGLE_CLIENT_ID
spring.security.oauth2.client.registration.google.client-secret=YOUR_GOOGLE_CLIENT_SECRET

The SecurityConfig class configures security for a Spring Boot application using OAuth2. It defines a SecurityFilterChain bean, which sets up security rules. The authorizeHttpRequests method ensures that all incoming requests require authentication. The .oauth2Login(Customizer.withDefaults()) line enables OAuth2 login functionality with default settings. Finally, the securityFilterChain method returns the configured security filter chain by calling http.build(). This setup ensures that the application is secure and supports OAuth2 authentication for users.

Accessing Your Application via Chrome

When developing and testing your Spring Boot application, it's crucial to know how to interact with it through Postman. If your application is running locally on port 8000, you can access it using the following base URL:

http://localhost:8000

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

we get the similar response like this

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

now we can access the end points.

GitHub Authentication

GitHub Authentication in Spring Boot allows users to log in using their GitHub accounts, streamlining the authentication process and enhancing security. By integrating GitHub as an OAuth 2.0 provider, your application can authenticate users through GitHub's trusted platform. This involves registering your application on GitHub to obtain a Client ID and Client Secret, which are then configured in your Spring Boot application. Users are redirected to GitHub for login, and upon successful authentication, they are redirected back to your application with an access token, allowing secure access to your protected resources. This integration is ideal for applications targeting developers and tech-savvy users.

create GitHub account and go to settings

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

in the left corner we get the developer settings

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

Navigate to OAuth Apps

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

click on create OAuth App

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

we get the interface like this

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

set ** Authorization callback URL ** according to your application port

http://localhost:8000/login/oauth2/code/github

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

and set Homepage URL

http://localhost:8000

after registering the Application we get the Client ID and Client Secret

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

now replace with the Application.properties file properties

spring.security.oauth2.client.registration.github.client-id=Ov23liBMLc5e1ItoONPx
spring.security.oauth2.client.registration.github.client-secret= 

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

Test the GitHub Login

Login with GitHub: When prompted, log in with your GitHub credentials.
Success Redirect: Upon successful authentication, you'll be redirected to the /home page of your application.

OAuth  Authentication in Spring Boot: A Guide to Integrating Google and GitHub Login

您可以在我的 GitHub 存储库上探索用户身份验证服务的完整源代码。该项目展示了各种功能,例如用户注册、登录和使用 JWT 进行身份验证的安全访问。请随意查看、贡献或将其用作您自己的项目的参考!

GitHub 存储库:https://github.com/ishrivasayush/oauth2-authentication-service

结论

使用 Spring Boot 实现 OAuth 2.0,使用 Google 和 GitHub 作为身份验证提供程序,是增强应用程序安全性和可用性的有效方法。通过允许用户使用现有帐户登录,您可以减少摩擦并提供更流畅的用户体验。同时,使用 JWT 保护您的 API 端点可确保只有经过身份验证的用户才能访问敏感资源。

通过本指南,我们涵盖了从在 Google 和 GitHub 上设置 OAuth 凭据到配置 Spring Boot 应用程序以处理身份验证和保护端点的所有内容。无论您是 OAuth 2.0 的新手还是希望将其集成到您的项目中,这些步骤都将帮助您构建安全且可扩展的身份验证系统。

安全是一个永无止境的旅程,但通过正确的工具和实践,您可以构建既安全又用户友好的应用程序。现在您已经有了坚实的基础,您可以通过添加更多提供商、自定义用户体验或更深入地研究 JWT 配置来进一步探索。快乐编码!

以上是Spring Boot 中的 OAuth 身份验证:Google 和 GitHub 登录集成指南的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Laravel 教程
1602
29
PHP教程
1504
276
Hashmap在Java内部如何工作? Hashmap在Java内部如何工作? Jul 15, 2025 am 03:10 AM

HashMap在Java中通过哈希表实现键值对存储,其核心在于快速定位数据位置。1.首先使用键的hashCode()方法生成哈希值,并通过位运算转换为数组索引;2.不同对象可能产生相同哈希值,导致冲突,此时以链表形式挂载节点,JDK8后链表过长(默认长度8)则转为红黑树提升效率;3.使用自定义类作键时必须重写equals()和hashCode()方法;4.HashMap动态扩容,当元素数超过容量乘以负载因子(默认0.75)时,扩容并重新哈希;5.HashMap非线程安全,多线程下应使用Concu

Java可选示例 Java可选示例 Jul 12, 2025 am 02:55 AM

Optional能清晰表达意图并减少null判断的代码噪音。1.Optional.ofNullable是处理可能为null对象的常用方式,如从map中取值时可结合orElse提供默认值,逻辑更清晰简洁;2.通过链式调用map实现嵌套取值,安全地避免NPE,任一环节为null则自动终止并返回默认值;3.filter可用于条件筛选,满足条件才继续执行后续操作,否则直接跳到orElse,适合轻量级业务判断;4.不建议过度使用Optional,如基本类型或简单逻辑中其反而增加复杂度,部分场景直接返回nu

如何处理Java中的字符编码问题? 如何处理Java中的字符编码问题? Jul 13, 2025 am 02:46 AM

处理Java中的字符编码问题,关键是在每一步都明确指定使用的编码。1.读写文本时始终指定编码,使用InputStreamReader和OutputStreamWriter并传入明确的字符集,避免依赖系统默认编码。2.在网络边界处理字符串时确保两端一致,设置正确的Content-Type头并用库显式指定编码。3.谨慎使用String.getBytes()和newString(byte[]),应始终手动指定StandardCharsets.UTF_8以避免平台差异导致的数据损坏。总之,通过在每个阶段

如何修复java.io.notserializable Exception? 如何修复java.io.notserializable Exception? Jul 12, 2025 am 03:07 AM

遇到java.io.NotSerializableException的核心解决方法是确保所有需序列化的类实现Serializable接口,并检查嵌套对象的序列化支持。1.给主类添加implementsSerializable;2.确保类中自定义字段对应的类也实现Serializable;3.用transient标记不需要序列化的字段;4.检查集合或嵌套对象中的非序列化类型;5.查看异常信息定位具体哪个类未实现接口;6.对无法修改的类考虑替换设计,如保存关键数据或使用可序列化的中间结构;7.考虑改

Java插座编程基本面和示例 Java插座编程基本面和示例 Jul 12, 2025 am 02:53 AM

JavaSocket编程是网络通信的基础,通过Socket实现客户端与服务器间的数据交换。1.Java中Socket分为客户端使用的Socket类和服务器端使用的ServerSocket类;2.编写Socket程序需先启动服务器监听端口,再由客户端发起连接;3.通信过程包括连接建立、数据读写及流关闭;4.注意事项包括避免端口冲突、正确配置IP地址、合理关闭资源及支持多客户端的方法。掌握这些即可实现基本的网络通信功能。

Java中的可比较与比较器 Java中的可比较与比较器 Jul 13, 2025 am 02:31 AM

在Java中,Comparable用于类内部定义默认排序规则,Comparator用于外部灵活定义多种排序逻辑。1.Comparable是类自身实现的接口,通过重写compareTo()方法定义自然顺序,适用于类有固定、最常用的排序方式,如String或Integer。2.Comparator是外部定义的函数式接口,通过compare()方法实现,适合同一类需要多种排序方式、无法修改类源码或排序逻辑经常变化的情况。两者区别在于Comparable只能定义一种排序逻辑且需修改类本身,而Compar

如何在Java的地图上迭代? 如何在Java的地图上迭代? Jul 13, 2025 am 02:54 AM

遍历Java中的Map有三种常用方法:1.使用entrySet同时获取键和值,适用于大多数场景;2.使用keySet或values分别遍历键或值;3.使用Java8的forEach简化代码结构。entrySet返回包含所有键值对的Set集合,每次循环获取Map.Entry对象,适合频繁访问键和值的情况;若只需键或值,可分别调用keySet()或values(),也可在遍历键时通过map.get(key)获取值;Java8中可通过Lambda表达式使用forEach((key,value)-&gt

Java中的'静态”关键字是什么? Java中的'静态”关键字是什么? Jul 13, 2025 am 02:51 AM

InJava,thestatickeywordmeansamemberbelongstotheclassitself,nottoinstances.Staticvariablesaresharedacrossallinstancesandaccessedwithoutobjectcreation,usefulforglobaltrackingorconstants.Staticmethodsoperateattheclasslevel,cannotaccessnon-staticmembers,

See all articles