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

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

王林
王林원래의
2024-08-31 18:31:17761검색

OAuth 2.0으로 보안 강화: Spring Boot에서 소셜 로그인 구현

최신 웹 개발 세계에서는 애플리케이션을 보호하고 사용자를 위해 최대한 원활한 인증을 제공하는 것이 최우선 과제입니다. OAuth 2.0은 API 보안에 도움이 될 뿐만 아니라 사용자가 Google 및 GitHub와 같은 플랫폼에서 기존 계정으로 로그인할 수 있게 해주는 강력한 도구입니다. 이를 통해 모든 사람이 작업을 더 쉽게 할 수 있습니다. 사용자는 또 다른 비밀번호를 기억할 필요가 없으며 개발자는 신뢰할 수 있는 인증 관리 방법을 얻게 됩니다.

이 블로그에서는 Spring Boot 애플리케이션에서 OAuth 2.0을 설정하는 방법을 단계별로 안내하겠습니다. 인증을 위해 Google과 GitHub를 모두 통합할 예정이므로 사용자는 로그인에 사용할 서비스를 선택할 수 있습니다. 또한 JWT(JSON 웹 토큰)를 사용하여 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 클라이언트" 종속성은 OAuth 2.0 인증을 Google 및 GitHub와 같은 제공업체와 통합하는 것을 단순화합니다. 사용자를 공급자의 로그인 페이지로 리디렉션하고, 토큰을 관리하고, API 엔드포인트를 보호하는 등 전체 OAuth 로그인 흐름을 처리합니다. 이 종속성을 추가하면 Spring Boot 애플리케이션에서 안전하고 사용자 친화적인 인증을 쉽게 활성화할 수 있습니다.

Spring Boot의 "Spring Web" 종속성은 웹 애플리케이션 개발에 매우 ​​중요합니다. RESTful API 생성, MVC 아키텍처 지원, HTML 보기 제공 기능과 같은 필수 기능을 제공합니다. Spring Web을 사용하면 HTTP 요청 및 응답을 쉽게 처리하고, 라우팅을 관리하고, 다른 Spring 구성 요소와 통합할 수 있으므로 강력한 웹 애플리케이션 구축의 기본 부분이 됩니다.

애플리케이션 구성

Google 및 GitHub에서 OAuth 2.0 인증을 위해 Spring Boot 애플리케이션을 설정하려면 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에서 얻은 자격 증명으로 바꾸세요.

OAuth 2.0 인증을 위해 Google 및 GitHub에 애플리케이션을 등록하려면 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

결론

Google 및 GitHub를 인증 공급자로 사용하여 Spring Boot로 OAuth 2.0을 구현하는 것은 애플리케이션의 보안과 유용성을 향상시키는 강력한 방법입니다. 사용자가 기존 계정으로 로그인할 수 있도록 허용하면 마찰을 줄이고 보다 원활한 사용자 경험을 제공할 수 있습니다. 동시에 JWT로 API 엔드포인트를 보호하면 인증된 사용자만 민감한 리소스에 액세스할 수 있습니다.

이 가이드를 통해 Google 및 GitHub에서 OAuth 자격 증명을 설정하는 것부터 인증을 처리하고 엔드포인트를 보호하도록 Spring Boot 애플리케이션을 구성하는 것까지 모든 것을 다루었습니다. OAuth 2.0을 처음 사용하거나 이를 프로젝트에 통합하려는 경우 이러한 단계는 안전하고 확장 가능한 인증 시스템을 구축하는 데 도움이 됩니다.

보안은 끝없는 여정이지만 올바른 도구와 방법을 사용하면 안전하고 사용자 친화적인 애플리케이션을 구축할 수 있습니다. 이제 탄탄한 기반이 마련되었으므로 더 많은 공급자를 추가하거나, 사용자 경험을 사용자 정의하거나, JWT 구성에 대해 더 자세히 알아보면서 더 자세히 탐색할 수 있습니다. 즐거운 코딩하세요!

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

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.