티스토리 뷰

IT/JAVA 및 Spring

[Spring Security] 구글 로그인 OAuth2.0 로그인 URL 변경하기 (authorizationEndpoint().baseUri)

주인장 진빼이

이번에 알아 볼 것은 authorizationEndPoint().baseUri() 설정하는 방법이다.

이를 통해 구글 로그인 링크를 커스터마이징 할 수 있다.

 

프로젝트 구성1

프로젝트 구성2

 

0x0. application.yml 설정

spring:
  application:
    name: my_todo123
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: 558621254640-mokd6ll52eta7jednpthjptg3a1hre42.apps.googleusercontent.com
            client-secret: < 키는 비밀 키이므로 공개할 수 없다>
            authorization-grant-type: authorization_code
            redirect-uri: "http://localhost:8081/mytodo_123/oauth2/client/test1"
            scope:
              - profile
              - email
server:
  port: 8081

 

 

0x1. WebSecurity 설정

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
    @Bean
    SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests().antMatchers("/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2Login()
                .authorizationEndpoint()
                .baseUri("/test777/auth"); // http://localhost:8081/test777/auth/<provider-id>

        return http.build();
    }
}

 

0x2. baseUri 설정하기

아래는 authrizationEndpoint baseUri의 기본값이다.

만약 baseUri를 별도로 설정하지 않았다면

http://localhost:8081/oauth2authorization/google 으로 접속해야 로그인 화면이 나타난다.

/oauth2/authorization/<provider-id>

 

baseUri를 "/test777/auth" 로 설정한 경우 아래 링크에 색칠한 부분은 baseUrl + baseUri를 의미하고

http://localhost:8081/test777/auth/google

 

뒤에 + "/google" 같이 프로바이더 이름이 들어가면 로그인 창이 성공적으로 표시되는 것을 볼 수 있다.

 

0x3. 결과

구글 로그인에 성공하면 아래 주소로 redirect 된다.

색칠한 부분은 구글 OAuth2.0 Client ID 등록 과정 중 URI로 등록된 주소이다.

http://localhost:8081/mytodo_123/oauth2/client/test1?state=nhEWGZAMPcxK6B_Wg1zio0qKvXLaouUf0smwBCOFia4%3D&code=4%2F0AfgeXvtI05Gb83AiO1AjACP6jpYq2uVfKl22e0AunbjGaAd34scikLZ0aQ_pIH4BQ_1WIA&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid&authuser=0&prompt=consent

 

넘겨준 URL에서 code prameter를 파싱하여 Key Value 형태로 만들어 객체에 담아

직접 수동으로 google resource server에게 req하여 JWT 토큰을 발행 받거나

redirect_uri 와 시큐리티 redirectionEndpoint().baseUri()를 일치시켜

토큰, 로그인 처리를 시큐리티 CustomOAuth2UserService구현체에 위임할 수 있다.

 

[주의사항] application.yml에 설정한 redirect-uri 와 구글에 설정된 uri가 서로 동일해야 한다.

 

예제 프로젝트 파일:

mytodo123.zip
0.12MB

 

 

참고:

https://docs.spring.io/spring-security/site/docs/5.0.7.RELEASE/reference/html/oauth2login-advanced.html

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함