console.cloud.google.com/home/

으로 이동하여 왼쪽 리스트에서 API 및 서비스 -> 사용자 인증 정보 -> 사용자 인증 정보 만들기 -> OAuth클라이언트 ID 생성

여기서 앱 이름과 인증 코드를 Redirect 받을 URL(승인된 리디렉션 URI)을 추가합니다.
저는 로컬 환경과 서버 환경 둘 다 받아야 하기 때문에 2개가 되어있습니다.

프로젝트로 들어가서 클라이언트 ID와 보안 비밀을 따로 보관해 두세요

본 포스팅에 사용하는 API문서
developers.google.com/identity/protocols/oauth2/web-server

 

Using OAuth 2.0 for Web Server Applications  |  Google ID 플랫폼

This document explains how web server applications use Google API Client Libraries or Google OAuth 2.0 endpoints to implement OAuth 2.0 authorization to access Google APIs. OAuth 2.0 allows users to share specific data with an application while keeping the

developers.google.com

보내야 하는곳은 https://accounts.google.com/o/oauth2/v2/auth 
이며 JSP에서 시작하겠습니다.

<button class="btn btn-primary" id="googleLoginBtn">구글 로그인</button>

const onClickGoogleLogin = function(e) {
	    	//구글서버로 인증코드 발급 요청
	 		window.location.replace("https://accounts.google.com/o/oauth2/v2/auth?
			client_id=본인클라이언트ID&
			redirect_uri=http://localhost:8080/score/User/google/auth(위에서 추가한 URL)&
			response_type=code&
			scope=email%20profile%20openid&
			access_type=offline");
	 	}


button을 누르면 js에 의해서 요청합니다.

누르게 되면

 

저희가 알던화면으로 오게 됩니다 하단에 권한에 대해 나와있습니다.
동의하면 같은경우에는 저희가 생성했던 OAuth 설정에 동의 화면 탭에 따로 나와있습니다.

동의 화면에 수정하고 scope 파라미터에 지정해두지 않으면 넘어오지 않으니 참고하세요

사용자가 아이디를 선택해 로그인하면 인증 코드가 발급이 됩니다.

이때 아까 인증코드를 요청할 때 함께 넘겼던 url로 요청됩니다.


서버 측에 요청 및 응답을 받기 위한 모델을 만들겠습니다.

public class GoogleOAuthRequest {
	private String redirectUri;
	private String clientId;
	private String clientSecret;
	private String code;
	private String responseType;
	private String scope;
	private String accessType;
	private String grantType;
	private String state;
	private String includeGrantedScopes;
	private String loginHint;
	private String prompt;
	
	public String getRedirectUri() {
		return redirectUri;
	}
	public void setRedirectUri(String redirectUri) {
		this.redirectUri = redirectUri;
	}
	public String getClientId() {
		return clientId;
	}
	public void setClientId(String clientId) {
		this.clientId = clientId;
	}
	public String getClientSecret() {
		return clientSecret;
	}
	public void setClientSecret(String clientSecret) {
		this.clientSecret = clientSecret;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getResponseType() {
		return responseType;
	}
	public void setResponseType(String responseType) {
		this.responseType = responseType;
	}
	public String getScope() {
		return scope;
	}
	public void setScope(String scope) {
		this.scope = scope;
	}
	public String getAccessType() {
		return accessType;
	}
	public void setAccessType(String accessType) {
		this.accessType = accessType;
	}
	public String getGrantType() {
		return grantType;
	}
	public void setGrantType(String grantType) {
		this.grantType = grantType;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public String getIncludeGrantedScopes() {
		return includeGrantedScopes;
	}
	public void setIncludeGrantedScopes(String includeGrantedScopes) {
		this.includeGrantedScopes = includeGrantedScopes;
	}
	public String getLoginHint() {
		return loginHint;
	}
	public void setLoginHint(String loginHint) {
		this.loginHint = loginHint;
	}
	public String getPrompt() {
		return prompt;
	}
	public void setPrompt(String prompt) {
		this.prompt = prompt;
	}
	
}
public class GoogleOAuthResponse {
	private String accessToken;
	private String expiresIn;
	private String refreshToken;
	private String scope;
	private String tokenType;
	private String idToken;
	
	public String getAccessToken() {
		return accessToken;
	}
	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}
	public String getExpiresIn() {
		return expiresIn;
	}
	public void setExpiresIn(String expiresIn) {
		this.expiresIn = expiresIn;
	}
	public String getRefreshToken() {
		return refreshToken;
	}
	public void setRefreshToken(String refreshToken) {
		this.refreshToken = refreshToken;
	}
	public String getScope() {
		return scope;
	}
	public void setScope(String scope) {
		this.scope = scope;
	}
	public String getTokenType() {
		return tokenType;
	}
	public void setTokenType(String tokenType) {
		this.tokenType = tokenType;
	}
	public String getIdToken() {
		return idToken;
	}
	public void setIdToken(String idToken) {
		this.idToken = idToken;
	}
	
}
@RequestMapping(value = "/google/auth", method = RequestMethod.GET)
	public String googleAuth(Model model, @RequestParam(value = "code") String authCode,HttpServletRequest request)
			throws Exception {
		
		//HTTP Request를 위한 RestTemplate
		RestTemplate restTemplate = new RestTemplate();

		//Google OAuth Access Token 요청을 위한 파라미터 세팅
		GoogleOAuthRequest googleOAuthRequestParam =  new GoogleOAuthRequest();
		googleOAuthRequestParam.setClientId("1028174609911-433j0ub6ablgbnubj4i6bvm0dclv23je.apps.googleusercontent.com");
		googleOAuthRequestParam.setClientSecret("ALSEXcRMY_WyYA_ogxYAAXvp");
		googleOAuthRequestParam.setCode(authCode);
		googleOAuthRequestParam.setRedirectUri("http://localhost:8080/score/User/google/auth");
		googleOAuthRequestParam.setGrantType("authorization_code");
		
		//JSON 파싱을 위한 기본값 세팅
		//요청시 파라미터는 스네이크 케이스로 세팅되므로 Object mapper에 미리 설정해준다.
		ObjectMapper mapper = new ObjectMapper();
		mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
		mapper.setSerializationInclusion(Include.NON_NULL);

		//AccessToken 발급 요청
		ResponseEntity<String> resultEntity = restTemplate.postForEntity("https://oauth2.googleapis.com/token", googleOAuthRequestParam, String.class);

		//Token Request
		GoogleOAuthResponse result = mapper.readValue(resultEntity.getBody(), new TypeReference<GoogleOAuthResponse>() {
		});

		//ID Token만 추출 (사용자의 정보는 jwt로 인코딩 되어있다)
		String jwtToken = result.getIdToken();
		String requestUrl = UriComponentsBuilder.fromHttpUrl("https://oauth2.googleapis.com/tokeninfo").queryParam("id_token", jwtToken).toUriString();
		
		String resultJson = restTemplate.getForObject(requestUrl, String.class);
		
		Map<String,String> userInfo = mapper.readValue(resultJson, new TypeReference<Map<String, String>>(){});
		model.addAllAttributes(userInfo);
		model.addAttribute("token", result.getAccessToken());
		
		return "사용할 페이지";
	}

userinfo 안에 내용을 확인할수 있다.

나는 name,email,id 를 확인해서 최초 구글 로그인 시 해당 내용으로 회원가입으로 이동시킨다

그 이후에 접근하는 로그인은 DB에서 id값을 조회해 있으면 세션에 해당 값을 저장해서 로그인시킨다.

'Backend > API' 카테고리의 다른 글

[API] Java에서 JSON값 활용하기  (0) 2020.11.25
[API]Java 유튜브 검색 결과 Json으로 받기  (0) 2020.11.24