Spring Boot의 OAuth 인증: Google과 GitHub 로그인 통합 가이드

王林
풀어 주다: 2024-08-31 18:31:17
원래의
599명이 탐색했습니다.

Enhance Security with OAuth 2.0: Implementing Social Logins in Spring Boot

In the world of modern web development, securing your applications and making authentication as smooth as possible for users is a top priority. That’s where OAuth 2.0 comes in—it’s a powerful tool that not only helps secure your APIs but also lets users log in with their existing accounts from platforms like Google and GitHub. This makes things easier for everyone: users don’t need to remember yet another password, and developers get a reliable way to manage authentication.

In this blog, I’ll take you step by step through how to set up OAuth 2.0 in a Spring Boot application. We’ll be integrating both Google and GitHub for authentication, so your users can choose which service they want to use to log in. I’ll also show you how to protect your API endpoints using JWT (JSON Web Tokens), ensuring that only authenticated users can access the resources they’re supposed to.

Whether you’re building a new app or adding security to an existing one, this guide will give you the tools you need to keep your Spring Boot application secure and user-friendly.

Visit https://start.spring.io/

create the project

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

Download the zip and extract it and load the project to your IDE.

The "OAuth2 Client" dependency in Spring Boot simplifies integrating OAuth 2.0 authentication with providers like Google and GitHub. It handles the entire OAuth login flow, including redirecting users to the provider's login page, managing tokens, and securing API endpoints. By adding this dependency, you can easily enable secure and user-friendly authentication in your Spring Boot application.

The "Spring Web" dependency in Spring Boot is crucial for developing web applications. It provides essential features like RESTful API creation, MVC architecture support, and the ability to serve HTML views. With Spring Web, you can easily handle HTTP requests and responses, manage routing, and integrate with other Spring components, making it a foundational part of building robust web applications.

Application Configuration

To set up your Spring Boot application for OAuth 2.0 authentication with Google and GitHub, you'll need to configure the application.properties file. This file contains essential settings for your application, including OAuth client credentials, logging levels, and JWT configurations.

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 Client Configurations:Replace YOUR_GOOGLE_CLIENT_ID, YOUR_GOOGLE_CLIENT_SECRET, YOUR_GITHUB_CLIENT_ID, and YOUR_GITHUB_CLIENT_SECRET with the credentials you obtain from Google and GitHub when you register your application.

To register your application with Google and GitHub for OAuth 2.0 authentication, we need to go https://console.cloud.google.com

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

click on API Services

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

Credentials -> create Credentials -> OAuth client ID

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

OAuth client ID -> Create OAuth client ID

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

selectApplication typetoweb Application

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

give application name

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

setAuthorized redirect URIswith this URL and here our application is running on 8000 port so application port is 8000. then click on create

http://localhost:8000/login/oauth2/code/google
로그인 후 복사

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

after that OAuth client is created and we get the client ID and the Client secret.

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
로그인 후 복사

TheSecurityConfigclass 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 thedeveloper 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 oncreate 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 setHomepage URL

http://localhost:8000
로그인 후 복사

after registering the Application we get theClient 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

Vous pouvez explorer le code source complet du service d'authentification utilisateur sur mon référentiel GitHub. Ce projet présente diverses fonctionnalités telles que l'enregistrement des utilisateurs, la connexion et l'accès sécurisé à l'aide de JWT pour l'authentification. N'hésitez pas à le consulter, à contribuer ou à l'utiliser comme référence pour vos propres projets !

Dépôt GitHub : https://github.com/ishrivasayush/oauth2-authentication-service

Conclusion

La mise en œuvre d'OAuth 2.0 avec Spring Boot, en utilisant Google et GitHub comme fournisseurs d'authentification, est un moyen puissant d'améliorer la sécurité et la convivialité de votre application. En permettant aux utilisateurs de se connecter avec leurs comptes existants, vous réduisez les frictions et offrez une expérience utilisateur plus fluide. Dans le même temps, la sécurisation de vos points de terminaison d'API avec JWT garantit que seuls les utilisateurs authentifiés ont accès aux ressources sensibles.

Dans ce guide, nous avons tout couvert, depuis la configuration des informations d'identification OAuth sur Google et GitHub jusqu'à la configuration de votre application Spring Boot pour gérer l'authentification et protéger vos points de terminaison. Que vous soyez nouveau sur OAuth 2.0 ou que vous cherchiez à l'intégrer dans vos projets, ces étapes vous aideront à créer un système d'authentification sécurisé et évolutif.

La sécurité est un voyage sans fin, mais avec les bons outils et pratiques, vous pouvez créer des applications à la fois sûres et conviviales. Maintenant que vous disposez d'une base solide, vous pouvez explorer davantage en ajoutant d'autres fournisseurs, en personnalisant l'expérience utilisateur ou en approfondissant les configurations JWT. Bon codage !

위 내용은 Spring Boot의 OAuth 인증: Google과 GitHub 로그인 통합 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!