Spring Security 연동 (4) (UserDetailsService, DTO, Controller)
Spring Security 연동 (4) (UserDetailsService, DTO, Controller)
Spring Security 연동 (3) (JPA 처리, Entity, Repository, Test) Spring Security 연동 (3) (JPA 처리, Entity, Repository, Test) Spring Security 연동 (2) (PasswordEncoder, CSRF, logout) Spring Security 연동 (2) (PasswordEncoder, CSRF, logout) Spring
soohykeee.tistory.com
이번엔 소셜 로그인 기능을 추가해줄것이다.
Spring Security를 사용할 때 가장 많이 요구되는 기능은 '소셜 로그인' 이라고 할 수 있다. 소셜 로그인은 국내외 사이트에 등에서 제공하는 로그인 통합 기능을 이용해서 사용자가 별도의 회원가입 없이 자동으로 로그인이 이루어 지도록 구성하는 것이다.
구글 로그인 처리
[개념] OAuth 란 무엇인가?
OAuth 란? OAuth는 Open Authorization의 약자로, 인터넷 사용자들이 비밀번호를 제공하지 않고 다른 웹사이트 상의 자신들의 정보에 대해 웹사이트나 애플리케이션의 접근 권한을 부여할 수 있는 공통
soohykeee.tistory.com
OAuth에 대한 설명은 위에 간단히 정리해놓았다.
구글 프로젝트 등록
프로젝트 내 설정
build.gradle 내에 아래의 OAuth 사용을 위한 의존성을 추가해준다.
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
의존성을 추가해준 후, application-oauth.properties를 추가해준다. 앞으로 여러개의 OAuth를 추가해줄 예정이라면 다음과 같이 따로 properties 파일을 추가해준 후 작성해주는 것이 더 낫다. 또한 유출되서는 안되는 Client ID, Client Secret 을 포함해야 하므로 따로 빼서 사용하는 것이 더 낫다.
application-oauth.properties에 해당 코드를 작성해준다.
spring.security.oauth2.client.registration.google.client-id= 생성된 클라이언트 아이디
spring.security.oauth2.client.registration.google.client-secret= 생성된 클라이언트 비밀번호
spring.security.oauth2.client.registration.google.scope=email
application.yml에는 해당 코드를 추가해준다.
spring:
profiles:
include: oauth
SpringConfig 수정
@Configuration
@Log4j2
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/sample/all").permitAll()
.antMatchers("/sample/member").hasRole("USER")
.antMatchers("/sample/admin").hasRole("ADMIN");
http.formLogin();
http.csrf().disable();
http.oauth2Login();
}
}
SpirngConfig 클래스를 위와 같이 수정해준 후, 프로젝트를 실행하여 '/sampel/member'에 접근했을 때, 로그인 화면에서 Google로그인 링크가 추가된것을 확인할 수 있다.
또한 구글 계정으로 로그인 시, 성공적으로 로그인이 되고, 접근이 되는것을 확인할 수 있다.