github oauth를 활용하여 oauth를 구현해보는 실습을 할 것 이다.
Github 및 Spring Security 로 어플리케이션 보안
spring-boot-starter-oauth2-client
소셜 로그인(github) 을 하려면 Spring Security Oauth 2.0 클라이언트 스타터를 포함해야한다.
Github를 인증 provider 로서 앱을 구성하기
application을 다음과 같이 등록한다.
http://localhost:8080
OAuth redirection URI 는 최종 사용자 에이전트가 GitHub에 인증하고 application 승인 페이지에서 액세스 권한을 부여한 후 다시 리디렉션되는 어플리케이션의 경로이다.
아래는 기본 리디렉션 URI 템플릿이다.
{baseUrl}/login/oauth2/code/{registrationId}.
RegistrationId 는 의 고유 식별자
그런 다음 GitHub에 대한 링크를 아래와 같이 만들어야한다. (application.yml)
spring:
security:
oauth2:
client:
registration:
github:
clientId: github-client-id
clientSecret: github-client-secret
실행되는 순서
http://localhost:8080 홈페이지를 방문
↓
홈페이지 대신 GitHub로 로그인하도록 리디렉션되어야한다. 이때 GitHub에서 승인을 허락하면 로컬 앱으로 다시 리디렉션되고 홈페이지가 표시된다.
↓
Single Sign-On 한번 로그인된 상태를 유지하면 쿠키나 캐시된 데이터가 없는 새로운 브라우저에서 앱을 열더라도 이 로컬 앱으로 다시 인증할 필요가 없다.
무슨일이 일어나는걸까?
방금 작성한 앱은 client application이다.
1. 인증 코드 부여 방식을 사용하여 GitHub(인증 서버)에서 액세스 토큰을 얻는다.
2. 리소스 서버로서의 GitHub
- 얻은 액세스 토큰을 사용하여 GitHub에 로그인 ID와 이름등의 개인 정보를 요청한다.
- 이 단계에서 GitHub는 리소스 서버 역할을 하며, 전송된 토큰을 디코딩하고 사용자 세부 정보에 대한 액세스 권한을 앱에 부여한다.
3. 프로세스가 성공하면 앱은 사용자 세부 정보를 Spring Security 컨텍스트에 삽입하여 인증을 받는다.
4. 브라우저 도구를 사용하여 네트워크 트래픽을 따라가면 GitHub를 통해 앞뒤로 리디렉션되는 것을 볼 수 있다.
마지막으로 새 헤더(Set-Cookie)가 있는 홈 페이지로 돌아온다.
5. 인증 세부 정보 토큰 : JSESSIONID 쿠키는 Spring 애플리케이션에 대한 인증 세부 정보 토큰이다.
@AuthenticationPrincipalOauth2User 이 어노테이션을 사용하여 user 정보를 사용할 수 있다. spring security 가 default 로 홈페이지에 대한 액세스 인증을 요구한다.(모든 요청에대해서) 이것을 하지 않게 하려면 설정이 필요한다.
@SpringBootApplication
@RestController
public class SocialApplication extends WebSecurityConfigurerAdapter {
// ...
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(a -> a
.antMatchers("/", "/error", "/webjars/**").permitAll()
.anyRequest().authenticated()
)
.exceptionHandling(e -> e
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
)
.oauth2Login();
// @formatter:on
}
}
WebSecurityConfigurerAdapterSpring Boot는 다음과 같이 주석이 달린 클래스 에 특별한 의미를 부여한다. @SpringBootApplication. 이를 사용하여 OAuth 2.0 인증 프로세서를 전달하는 보안 필터 체인을 구성한다.
로그아웃 같은 더 자세한 설명은 아래의 링크에서 알 수 있다.
reference[https://spring.io/guides/tutorials/spring-boot-oauth2#_social_login_simple]
Getting Started | Spring Boot and OAuth2
In this section, we modify the click app we built by adding a button that allows the user to log out of the app. This seems like a simple feature, but it requires a bit of care to implement, so it’s worth spending some time discussing exactly how to do i
spring.io
'Spring' 카테고리의 다른 글
Spring Security와 JWT (0) | 2024.06.10 |
---|---|
Spring Security Architecture 이해하기 (2) | 2024.06.10 |
[토비의 스프링] 스프링의 이해와 원리 (1) | 2024.03.23 |
static 과 Bean (0) | 2024.02.15 |