-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feature/kakao login #16
Merged
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c3e71ad
feat : CORS ์ค์ ๋ฐ ์นด์นด์ค ๋ก๊ทธ์ธ ๊ตฌํ
ErranderLee 0779162
Merge branch 'dev' of https://github.com/Ajou-Travely/BE-API into feaโฆ
ErranderLee aca3927
feat :
ErranderLee 9e83461
test :
ErranderLee e2220d6
feat :
ErranderLee 0cbca94
refactor :
ErranderLee aabcb76
refactor :
ErranderLee File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package com.ajou.travely.config; | ||
|
||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.web.servlet.config.annotation.CorsRegistry; | ||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; | ||
|
||
@Configuration | ||
public class CorsConfig implements WebMvcConfigurer { | ||
@Bean | ||
public WebMvcConfigurer corsConfigurer() { | ||
return new WebMvcConfigurer() { | ||
@Override | ||
public void addCorsMappings(CorsRegistry registry) { | ||
registry.addMapping("/**").allowedOrigins("http://localhost:3000") | ||
.allowCredentials(true); | ||
} | ||
}; | ||
} | ||
} |
50 changes: 50 additions & 0 deletions
50
src/main/java/com/ajou/travely/config/CustomAuthentication.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package com.ajou.travely.config; | ||
|
||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.GrantedAuthority; | ||
|
||
import java.io.Serializable; | ||
import java.util.Collection; | ||
|
||
public class CustomAuthentication implements Authentication, Serializable { | ||
private final Long kakaoId; | ||
|
||
public CustomAuthentication(Long kakaoId) { | ||
this.kakaoId = kakaoId; | ||
} | ||
|
||
@Override | ||
public Collection<? extends GrantedAuthority> getAuthorities() { | ||
return null; | ||
} | ||
|
||
@Override | ||
public Object getCredentials() { | ||
return null; | ||
} | ||
|
||
@Override | ||
public Object getDetails() { | ||
return kakaoId; | ||
} | ||
|
||
@Override | ||
public Object getPrincipal() { | ||
return null; | ||
} | ||
|
||
@Override | ||
public boolean isAuthenticated() { | ||
return true; | ||
} | ||
|
||
@Override | ||
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { | ||
|
||
} | ||
|
||
@Override | ||
public String getName() { | ||
return null; | ||
} | ||
} |
13 changes: 13 additions & 0 deletions
13
src/main/java/com/ajou/travely/config/RestTemplateConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package com.ajou.travely.config; | ||
|
||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.web.client.RestTemplate; | ||
|
||
@Configuration | ||
public class RestTemplateConfig { | ||
@Bean | ||
public RestTemplate restTemplate() { | ||
return new RestTemplate(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
package com.ajou.travely.config; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
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.config.annotation.web.configuration.WebSecurityConfigurerAdapter; | ||
|
||
@RequiredArgsConstructor | ||
@Configuration | ||
@EnableWebSecurity | ||
public class SecurityConfig extends WebSecurityConfigurerAdapter { | ||
@Override | ||
protected void configure(HttpSecurity http) throws Exception { | ||
http.csrf().disable(); | ||
http.authorizeRequests() | ||
.antMatchers("/**").permitAll(); | ||
} | ||
} |
33 changes: 33 additions & 0 deletions
33
src/main/java/com/ajou/travely/controller/auth/AuthController.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
package com.ajou.travely.controller.auth; | ||
|
||
import com.ajou.travely.service.AuthService; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
import org.json.simple.JSONObject; | ||
import org.springframework.web.bind.annotation.GetMapping; | ||
import org.springframework.web.bind.annotation.RequestHeader; | ||
import org.springframework.web.bind.annotation.RequestParam; | ||
import org.springframework.web.bind.annotation.RestController; | ||
|
||
|
||
import java.util.Optional; | ||
|
||
@RestController | ||
@RequiredArgsConstructor | ||
public class AuthController { | ||
private final AuthService authService; | ||
|
||
@GetMapping("/oauth2/authorization/kakao") | ||
public JSONObject login(@RequestParam("code") String code) { | ||
return authService.kakaoAuthentication(code); | ||
} | ||
|
||
@GetMapping("/isLogin") | ||
public Boolean isLogin(@RequestHeader("Cookie") Optional<Object> header) { | ||
if (header.isPresent()) { | ||
return true; | ||
} else { | ||
return false; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
13 changes: 13 additions & 0 deletions
13
src/main/java/com/ajou/travely/domain/AuthorizationKakao.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package com.ajou.travely.domain; | ||
|
||
import lombok.Getter; | ||
|
||
@Getter | ||
public class AuthorizationKakao { | ||
private String access_token; | ||
private String token_type; | ||
private String refresh_token; | ||
private String expires_in; | ||
private String scope; | ||
private String refresh_token_expires_in; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package com.ajou.travely.service; | ||
|
||
import com.ajou.travely.domain.AuthorizationKakao; | ||
import lombok.RequiredArgsConstructor; | ||
import org.json.simple.JSONObject; | ||
import org.springframework.stereotype.Service; | ||
|
||
@Service | ||
@RequiredArgsConstructor | ||
public class AuthService { | ||
private final Oauth2Service oauth2Service; | ||
|
||
public JSONObject kakaoAuthentication(String code) { | ||
AuthorizationKakao authorizationKakao = oauth2Service.callTokenApi(code); | ||
JSONObject userInfoFromKakao = oauth2Service.callGetUserByAccessToken(authorizationKakao.getAccess_token()); | ||
Long kakaoId = (Long) userInfoFromKakao.get("id"); | ||
JSONObject result = oauth2Service.setSessionOrRedirectToSignUp(kakaoId); | ||
return result; | ||
} | ||
} |
116 changes: 116 additions & 0 deletions
116
src/main/java/com/ajou/travely/service/Oauth2Service.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
package com.ajou.travely.service; | ||
|
||
import com.ajou.travely.config.CustomAuthentication; | ||
import com.ajou.travely.domain.AuthorizationKakao; | ||
import com.ajou.travely.domain.user.User; | ||
import com.ajou.travely.repository.UserRepository; | ||
import com.fasterxml.jackson.core.JsonProcessingException; | ||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import lombok.RequiredArgsConstructor; | ||
import org.json.simple.JSONObject; | ||
import org.json.simple.parser.JSONParser; | ||
import org.json.simple.parser.ParseException; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.http.*; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.GrantedAuthority; | ||
import org.springframework.security.core.context.SecurityContext; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.stereotype.Service; | ||
import org.springframework.util.LinkedMultiValueMap; | ||
import org.springframework.util.MultiValueMap; | ||
import org.springframework.web.client.RestClientException; | ||
import org.springframework.web.client.RestTemplate; | ||
|
||
import java.io.Serializable; | ||
import java.util.Collection; | ||
import java.util.HashMap; | ||
import java.util.Map; | ||
import java.util.Optional; | ||
|
||
@Service | ||
@RequiredArgsConstructor | ||
public class Oauth2Service { | ||
private final UserRepository userRepository; | ||
private final RestTemplate restTemplate; | ||
private final ObjectMapper objectMapper; | ||
@Value("${auth.kakaoOauth2ClinetId}") | ||
private String kakaoOauth2ClinetId; | ||
@Value("${auth.frontendRedirectUrl}") | ||
private String frontendRedirectUrl; | ||
|
||
public AuthorizationKakao callTokenApi(String code) { | ||
String grantType = "authorization_code"; | ||
HttpHeaders headers = new HttpHeaders(); | ||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); | ||
|
||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); | ||
params.add("grant_type", grantType); | ||
params.add("client_id", kakaoOauth2ClinetId); | ||
params.add("redirect_uri", frontendRedirectUrl + "oauth/kakao/callback"); | ||
params.add("code", code); | ||
|
||
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers); | ||
System.out.println("request.getBody() = " + request.getBody()); | ||
String url = "https://kauth.kakao.com/oauth/token"; | ||
try { | ||
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class); | ||
System.out.println("response.getBody() = " + response.getBody()); | ||
System.out.println("response.getHeaders() = " + response.getHeaders()); | ||
AuthorizationKakao authorization = objectMapper.readValue(response.getBody(), AuthorizationKakao.class); | ||
|
||
return authorization; | ||
} catch (RestClientException | JsonProcessingException ex) { | ||
ex.printStackTrace(); | ||
throw new RestClientException("error"); | ||
} | ||
} | ||
|
||
public JSONObject callGetUserByAccessToken(String accessToken) { | ||
HttpHeaders headers = new HttpHeaders(); | ||
headers.set("Authorization", "Bearer " + accessToken); | ||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); | ||
|
||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); | ||
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers); | ||
|
||
String url = "https://kapi.kakao.com/v2/user/me"; | ||
try { | ||
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class); | ||
// SecurityContext context = SecurityContextHolder.getContext(); | ||
JSONObject userInfo = StringToJson(response.getBody()); | ||
// System.out.println("userInfo.get(\"id\") = " + userInfo.get("id")); | ||
// JSONObject properties = (JSONObject) userInfo.get("properties"); | ||
// System.out.println("properties.get(\"nickname\") = " + properties.get("nickname")); | ||
// Long kakaoId = (Long) userInfo.get("id"); | ||
// context.setAuthentication(new CustomAuthentication(kakaoId)); | ||
return userInfo; | ||
}catch (RestClientException | ParseException ex) { | ||
ex.printStackTrace(); | ||
throw new RestClientException("error"); | ||
} | ||
} | ||
|
||
public JSONObject setSessionOrRedirectToSignUp(Long kakaoId) { | ||
Optional<User> user = userRepository.findByKakaoId(kakaoId); | ||
JSONObject result = new JSONObject(); | ||
if(!user.isPresent()) { | ||
result.put("status", 301); | ||
result.put("kakaoId", kakaoId); | ||
return result; | ||
} else { | ||
SecurityContext context = SecurityContextHolder.getContext(); | ||
User exUser = user.get(); | ||
context.setAuthentication(new CustomAuthentication(kakaoId)); | ||
result.put("status", 200); | ||
} | ||
return result; | ||
} | ||
public JSONObject StringToJson(String userInfo) throws ParseException { | ||
JSONParser jsonParser = new JSONParser(); | ||
Object object = jsonParser.parse(userInfo); | ||
JSONObject jsonObject = (JSONObject) object; | ||
return jsonObject; | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
๋ฉ์๋๋ช ์ ์๋ฌธ์๋ก ์์ํ๋๊ฒ ์ข์ ๊ฒ ๊ฐ์์!