Maison  >  Article  >  Java  >  Authentification OAuth dans Spring Boot : guide d'intégration de la connexion Google et GitHub

Authentification OAuth dans Spring Boot : guide d'intégration de la connexion Google et GitHub

王林
王林original
2024-08-31 18:31:17760parcourir

Améliorez la sécurité avec OAuth 2.0 : implémentation des connexions sociales dans Spring Boot

Dans le monde du développement Web moderne, sécuriser vos applications et rendre l'authentification aussi fluide que possible pour les utilisateurs est une priorité absolue. C'est là qu'intervient OAuth 2.0 : c'est un outil puissant qui non seulement aide à sécuriser vos API, mais permet également aux utilisateurs de se connecter avec leurs comptes existants à partir de plateformes comme Google et GitHub. Cela rend les choses plus faciles pour tout le monde : les utilisateurs n'ont pas besoin de se souvenir d'un énième mot de passe et les développeurs disposent d'un moyen fiable de gérer l'authentification.

Dans ce blog, je vais vous expliquer étape par étape comment configurer OAuth 2.0 dans une application Spring Boot. Nous intégrerons Google et GitHub pour l'authentification, afin que vos utilisateurs puissent choisir le service qu'ils souhaitent utiliser pour se connecter. Je vais également vous montrer comment protéger les points de terminaison de votre API à l'aide de JWT (JSON Web Tokens), en veillant à ce que uniquement les utilisateurs authentifiés peuvent accéder aux ressources auxquelles ils sont censés accéder.

Que vous créiez une nouvelle application ou que vous ajoutiez de la sécurité à une application existante, ce guide vous fournira les outils dont vous avez besoin pour garantir la sécurité et la convivialité de votre application Spring Boot.

Visitez https://start.spring.io/

créer le projet

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

Téléchargez le zip, extrayez-le et chargez le projet dans votre IDE.

La dépendance "OAuth2 Client" dans Spring Boot simplifie l'intégration de l'authentification OAuth 2.0 avec des fournisseurs comme Google et GitHub. Il gère l'intégralité du flux de connexion OAuth, y compris la redirection des utilisateurs vers la page de connexion du fournisseur, la gestion des jetons et la sécurisation des points de terminaison de l'API. En ajoutant cette dépendance, vous pouvez facilement activer une authentification sécurisée et conviviale dans votre application Spring Boot.

La dépendance "Spring Web" dans Spring Boot est cruciale pour le développement d'applications Web. Il fournit des fonctionnalités essentielles telles que la création d'API RESTful, la prise en charge de l'architecture MVC et la possibilité de servir des vues HTML. Avec Spring Web, vous pouvez facilement gérer les requêtes et les réponses HTTP, gérer le routage et intégrer d'autres composants Spring, ce qui en fait un élément fondamental de la création d'applications Web robustes.

Configuration des applications

Pour configurer votre application Spring Boot pour l'authentification OAuth 2.0 avec Google et GitHub, vous devrez configurer le fichier application.properties. Ce fichier contient les paramètres essentiels de votre application, notamment les informations d'identification du client OAuth, les niveaux de journalisation et les configurations 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

Configurations du client OAuth : Remplacez YOUR_GOOGLE_CLIENT_ID, YOUR_GOOGLE_CLIENT_SECRET, YOUR_GITHUB_CLIENT_ID et YOUR_GITHUB_CLIENT_SECRET par les informations d'identification que vous obtenez de Google et de GitHub lorsque vous enregistrez votre application.

Pour enregistrer votre application auprès de Google et GitHub pour l'authentification OAuth 2.0, nous devons aller sur https://console.cloud.google.com

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

cliquez sur Services API

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

Identifiants -> créer des informations d'identification -> ID client OAuth

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

ID client OAuth -> Créer un identifiant client OAuth

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

sélectionnez Type d'application pour Application Web

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

donner le nom de l'application

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

définissez les URI de redirection autorisés avec cette URL et ici notre application s'exécute sur le port 8000 donc le port de l'application est 8000. puis cliquez sur créer

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

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

après cela, le client OAuth est créé et nous obtenons l'ID client et le secret client.

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

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 !

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn