솔적솔적

Spring Boot Security - 구글 로그인,구글 회원 프로필 정보 받기 본문

Back-end/Spring Boot Security

Spring Boot Security - 구글 로그인,구글 회원 프로필 정보 받기

솔솔봄향기 2022. 2. 8. 03:20

우선 google api console로 들어가서 프로젝트 만들기

https://console.developers.google.com/apis

 

Google Cloud Platform

하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요.

accounts.google.com

URL은 

http://localhost:8080/login/oauth2/code/google

구글 로그인이 완료가 되면 서버쪽에서 코드를 돌려준다. 우리는 코드를받아 요청을할 때 필요한 것

 

다른 메모장에 옮겨 적어놓기! 

 

그리고 잠깐 oauth2-client 라이브러리가 등록되어져있는지 확인해보자.

pom.xml안에 등록되어있는지 확인.

 

application.yml

    security:
        oauth2:
        client:
        registration:
        google:
        client-id:아까 프로젝트만들 때 나왔던 ID
        client-secret:아까 프로젝트만들 때 나왔던 비밀번호
        scope:
        -email
        -profile

 

loginForm.html 안에 주소는 마음대로 적지말고

<h1>로그인 페이지</h1>

<form action="/login" method="POST">
<input type="text" name="username" placeholder="username"><br/>
<input type="password" name="password" placeholder="password"><br/>

<button>로그인</button>
</form>

<a href="/oauth2/authorization/google">구글로그인</a>
<a href="/joinForm">회원가입을 아직 하지 않으셨나요?</a>

 

SecurityConfig안에 추가

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{
	
	@Bean
	public BCryptPasswordEncoder encodePwd() {
		return new BCryptPasswordEncoder();
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable();
		http.authorizeRequests()
		.antMatchers("/user/**").authenticated()
		.antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")//이 권한이 있는 사람만 들어올 수 있게한다.
		.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
		.anyRequest().permitAll()
		.and()
		.formLogin()
		.loginPage("/loginForm") 
		.loginProcessingUrl("/login")
		.defaultSuccessUrl("/")
		.and() ---------------------------------> 이 부분 추가
		.oauth2Login()           ---------------> 이 부분 추가
		.loginPage("/loginForm");---------------> 이 부분 추가
	}
}

후 실행한다면 

여기까지 왔다면 정상작동, 이제 계정을 선택 한 후 다음페이지에 후처리 진행을 해야한다.

 

로그인이 완료한 뒤에 무엇을 돌려주냐면

1. 코드 받기(인증이 됐다는 것이다.)

2. 엑세스토큰(권한을 받고)

3. 사용자 프로필 정보를 가져와

4. 그 정보를 토대로 회원가입을 자동으로 진행시키기도한다.

5. 이메일, 전화번호, 이름, 아이디 외의 추가적인 정보가 필요없다면 우리는 기본적인 정보만 가져와서 회원가입을 시킨다. 

 

엑세스 토큰, 사용자 프로필 정보를 한 방에 받게하자. → userService(null);

 

SecurityConfig 안에 코드 추가

위에 
    @Autowired
	private PrincipalOauth2UserService prinOauth2UserService;
	
    
아래에
    .userInfoEndpoint()
	.userService(prinOauth2UserService);

 

config 패키지 안에 oauth 생성

여기에 후처리를 진행하는데, 후처리는 loadUser로 진행한다.

@Service
public class PrincipalOauth2UserService extends DefaultOAuth2UserService {
	//구글로 부터 받은 userRequest데이터에 대한 후처리 되는 함수
	@Override
	public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
		System.out.println("userRequest:"+userRequest);
		return super.loadUser(userRequest);
	}
}

하고 실행할 시 console창에 

코드 수정

@Service
public class PrincipalOauth2UserService extends DefaultOAuth2UserService {
	//구글로 부터 받은 userRequest데이터에 대한 후처리 되는 함수
	@Override
	public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
		System.out.println("getClientRegistration:"+userRequest.getClientRegistration());
		System.out.println("getAccessToken:"+userRequest.getAccessToken());
		System.out.println("getAttributes:"+super.loadUser(userRequest).getAttributes());
		return super.loadUser(userRequest);
	}
}

코드 수정 후 구글 로그인한 후 콘솔 창을 보면

정보들이 보여짐

User.java 안에 추가

	private String provider;
	private String providerId;

 

PrincipalOauth2UserService

받은 getAttributes정보로 강제 회원가입을 시켜야한다. 

 

[참고] : 인프런 - 스프링부트 시큐리티 & JWT 강의