[코드로 배우는 스프링부트] chapter11. 스프링 시큐리티 소셜 로그인 처리

이용준·2023년 6월 22일
0

  • Google OAuth

  • 여러개의 OAuth 사용한다면 별도의 설정 파일 생성하는 것이 나음

    • application.yml

      spring:
        profiles:
          include: oauth    
    • application-oauth.yml

      • .yml과 환경변수 매칭 방법 ${G_CLIENT_ID}
      security:
        oauth2:
          registration:
            google:
              client-id: ${GOOGLE_CLIENT_ID}
              client-secret: ${GOOGLE_CLIENT_SECRET}
      		- 환경변수 적용하기(Mac OS)
      (terminal)>> vi ~/.zshrc  # 편집기 열기
      
      export GOOGLE_CLIENT_ID = ""
      export GOOGLE_CLIENT_SECRET = ""
      :wq # 저장 후 종료
      
      (terminal)>> source ~/.zshrc  # 적용

2. 현재 프로젝트와 연동

  1. 소셜 로그인시 고려할 사항
  • 소셜 로그인시 사용자 이메일 정보 추출
  • 현 DB와 연동해 사용자 정보 관리
  • 기존 + 소셜 로그인 동일 적용

1) OAuth2UserService

  • UserDetailsService의 OAuth 버전
    • 구글 같은 서비스에서 로그인 처리 끝난 결과 가져오는 작업
  • DefaultOAuth2UserService 상속받는 클래스 구현
  • loadUser() 메서드 통해 사용자 이메일등 추출

3. 자동 회원 가입 후처리

  • 자동 회원가입 후 고민해야 할 사항

    • 패스워드가 하나로 고정되는 단점
    • 사용자의 이메일(email) 외 이름(name)을 닉네임처럼 사용할 수 없는 점
  • 로그인 관련 처리 제공 인터페이스

    1. AuthenticationSuccessHandler
    2. AuthenticationFailHandler

AuthenticationSuccessHandler

  • 로그인 성공 이후 처리 담당하는 security.handler 클래스 생성
  • AuthenticationSuccessHandler 인터페이스 구현
  • SecurityConfig에 SuccessHandler 메서드 추가

4. Remember me 와 @PreAuthorize

1) Remember me

  • 자동 로그인

  • 쿠키(HttpCookie) 사용하는 웹 인증 방식

  • Remember me 설정

    public class SecurityConfig{
      @Autowired
      private ClubUserDetailsService userDetailsService;
      ...
    
      public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        ...
        http.rememberMe()
          .tokenValiditySeconds(60*60*24*7);  // 쿠키 유지 시간
          .userDetailsService(userDetailsService); 
      }
    }

2) @PreAuthorize

  • 어노테이션(@EnableGlobalMethodSecurity) 통한 접근 제한
    • @EnableGlobalMethodSecurity, 어노테이션 기반 접근 제한 설정 가능
    • @EnableMethodSecurity(prePostEnabled = true) // default - true
  • 접근 제한이 필요한 컨트롤러의 메서드에 @PreAuthorize 적용
    • @PreAuthorize()의 value는 문자열로 된 표현식 삽입
    • \'#' 과 같은 특수 기호 및 authentication 같은 내장 변수 이용 가능
      @Controller
      public class SampleController{
        ..
        @PreAuthorize("#clubAuthMember != null && #clubAuthMember.username eq \"user1@aa.com\"")  
      @GetMapping("/admin")  
      public String exAdmin(@AuthenticationPrincipal ClubAuthMemberDTO clubAuthMember){  
        log.info(" ============= Admin Only ============");  
        log.info(clubAuthMember);  
      
        return "/sample/admin";  
      }
      }
profile
뚝딱뚝딱

0개의 댓글