Heim > Java > javaLernprogramm > Hauptteil

OAuth-Authentifizierung in Spring Boot: Ein Leitfaden zur Integration von Google- und GitHub-Login

王林
Freigeben: 2024-08-31 18:31:17
Original
677 Leute haben es durchsucht

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

Nach dem Login kopieren

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

select Application type to web 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

set Authorized redirect URIs with 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
Nach dem Login kopieren

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
Nach dem Login kopieren

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

Nach dem Login kopieren

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
Nach dem Login kopieren

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

and set Homepage URL

http://localhost:8000
Nach dem Login kopieren

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= 

Nach dem Login kopieren

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

Sie können den vollständigen Quellcode für den Benutzerauthentifizierungsdienst in meinem GitHub-Repository erkunden. Dieses Projekt stellt verschiedene Funktionen wie Benutzerregistrierung, Anmeldung und sicheren Zugriff mithilfe von JWT zur Authentifizierung vor. Probieren Sie es einfach aus, tragen Sie dazu bei oder nutzen Sie es als Referenz für Ihre eigenen Projekte!

GitHub-Repository: https://github.com/ishrivasayush/oauth2-authentication-service

Abschluss

Die Implementierung von OAuth 2.0 mit Spring Boot unter Verwendung von Google und GitHub als Authentifizierungsanbieter ist eine leistungsstarke Möglichkeit, die Sicherheit und Benutzerfreundlichkeit Ihrer Anwendung zu verbessern. Indem Sie Benutzern ermöglichen, sich mit ihren vorhandenen Konten anzumelden, reduzieren Sie Reibungsverluste und sorgen für ein reibungsloseres Benutzererlebnis. Gleichzeitig stellt die Sicherung Ihrer API-Endpunkte mit JWT sicher, dass nur authentifizierte Benutzer Zugriff auf vertrauliche Ressourcen haben.

In diesem Leitfaden haben wir alles abgedeckt, von der Einrichtung von OAuth-Anmeldeinformationen bei Google und GitHub bis hin zur Konfiguration Ihrer Spring Boot-Anwendung für die Authentifizierung und den Schutz Ihrer Endpunkte. Ganz gleich, ob Sie neu bei OAuth 2.0 sind oder es in Ihre Projekte integrieren möchten, diese Schritte helfen Ihnen beim Aufbau eines sicheren und skalierbaren Authentifizierungssystems.

Sicherheit ist eine nie endende Reise, aber mit den richtigen Tools und Vorgehensweisen können Sie Anwendungen erstellen, die sowohl sicher als auch benutzerfreundlich sind. Nachdem Sie nun über eine solide Grundlage verfügen, können Sie weitere Erkundungen durchführen, indem Sie weitere Anbieter hinzufügen, die Benutzererfahrung anpassen oder tiefer in JWT-Konfigurationen eintauchen. Viel Spaß beim Codieren!

Das obige ist der detaillierte Inhalt vonOAuth-Authentifizierung in Spring Boot: Ein Leitfaden zur Integration von Google- und GitHub-Login. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!