Skip to content

Commit

Permalink
🛠️Feat #23: [Security] User Security 완성
Browse files Browse the repository at this point in the history
🛠️Feat #23: [Security] User Security 완성
  • Loading branch information
DDonghyeo authored Jul 27, 2023
2 parents c4ccecb + d8298bb commit 430d5b1
Show file tree
Hide file tree
Showing 18 changed files with 633 additions and 21 deletions.
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ dependencies {
//gson
implementation 'com.google.code.gson:gson:2.8.8'

//jwt
implementation 'io.jsonwebtoken:jjwt:0.9.1'


}

tasks.named('test') {
Expand Down
12 changes: 12 additions & 0 deletions src/main/java/com/umc/DongnaeFriend/config/JwtConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.umc.DongnaeFriend.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JwtConfig {

@Value("${jwt.secret-key}")
public String SECRET_KEY;

}
33 changes: 33 additions & 0 deletions src/main/java/com/umc/DongnaeFriend/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.umc.DongnaeFriend.config;


import com.umc.DongnaeFriend.global.security.JwtTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private JwtTokenFilter jwtTokenFilter;


@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/user/login").permitAll() // 인증 없이 접근 허용하는 URL
.antMatchers("/user/reissuance").permitAll() // 인증 없이 접근 허용하는 URL
.anyRequest().authenticated(); // 그 외의 URL은 인증 필요
http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
}

// 나머지 코드는 이전 예제와 동일
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
Expand Down Expand Up @@ -35,9 +36,7 @@ public class accountBookSharingController {
@GetMapping("/search")

public ResponseEntity<?> searchAll(@RequestParam("keyword") String keyword, @RequestParam("category") int category, Pageable pageable) {
log.info("searching : " + keyword + category);
List<SharingDto.ListResponse> res = accountBookSharingService.searchByKeyword(keyword, category, pageable);
log.info("res ");
return ResponseEntity.ok(res);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import java.util.List;

@Repository
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
import com.umc.DongnaeFriend.domain.dongnae.dto.DongnaeBoardDto;
import com.umc.DongnaeFriend.domain.dongnae.respository.DongnaeBoardRepository;
import com.umc.DongnaeFriend.domain.dongnae.service.DongnaeBoardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.naming.AuthenticationException;
Expand All @@ -13,6 +15,7 @@
* [ 가계부 공유 ]
* */

@Slf4j
@RestController
@RequestMapping("/town-information")
public class DongnaeBoardController {
Expand Down Expand Up @@ -52,6 +55,9 @@ public ResponseEntity<?> getLocation() {
public ResponseEntity<?> getBoards(@RequestParam("keyword") String keyword,
@RequestParam("category") int category,
@RequestParam("sortBy") int sort) {


log.info("User Id: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
return ResponseEntity.ok(dongnaeBoardService.searchByKeyword(keyword, category, sort));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package com.umc.DongnaeFriend.domain.user.contorller;

import com.umc.DongnaeFriend.domain.user.dto.UserDto;
import com.umc.DongnaeFriend.domain.user.service.KakaoService;
import com.umc.DongnaeFriend.domain.user.service.UserService;
import com.umc.DongnaeFriend.global.exception.CustomException;
import com.umc.DongnaeFriend.global.exception.ErrorCode;
import com.umc.DongnaeFriend.global.util.JwtTokenProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

@Autowired
KakaoService kakaoService;

@Autowired
UserService userService;

@Autowired
JwtTokenProvider jwtTokenProvider;



/**
* 유저 로그인 / 회원가입
* 인증 절차
*/
@PostMapping("/login")
public ResponseEntity<?> userLogin(@RequestParam("accessToken") String accessToken, HttpServletRequest request, HttpServletResponse httpServletResponse) {
log.info("LoginController 진입");

// if (!type.equals("kakao")) {
// throw new CustomException(ErrorCode.SERVER_ERROR);
// }


try {
log.info("userLogin 진입");
//사용자 정보 가져오기
HashMap<String, Object> userInfo = kakaoService.getUserInfo(accessToken);

//사용자 확인 기존 회원 -> 넘어가고, 없는 회원 -> 회원가입

UserDto.Response response = userService.userValidation(userInfo);

return ResponseEntity.ok(response);

} catch (IOException e) {
throw new CustomException(ErrorCode.INVALID_AUTH_TOKEN);
}
}

@PostMapping("/user/reissuance")
public ResponseEntity<?> reiussnaceToken(String refreshToken) {
try {

//토큰 재발급
String access_token = userService.createAccessTokenFromRefreshToken(refreshToken);
return ResponseEntity.ok(access_token);
} catch (Exception e) {
// RefreshToken만료
throw new CustomException(ErrorCode.INVALID_REFRESH_TOKEN);
}
}



}
42 changes: 42 additions & 0 deletions src/main/java/com/umc/DongnaeFriend/domain/user/dto/UserDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.umc.DongnaeFriend.domain.user.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;

public class UserDto {

@Getter
@AllArgsConstructor
public static class Request {

String accessToken;

String type;

}

@Getter
@Builder
@AllArgsConstructor
public static class Response {

String accessToken;

String refreshToken;

}

@Getter
@AllArgsConstructor
public static class SignUpDto {

String nickName;

String email;

Long kakaoId;

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import com.umc.DongnaeFriend.domain.type.YesNo;
import javax.persistence.*;
import lombok.*;
import org.springframework.lang.Nullable;

@Getter
@Builder
Expand All @@ -28,7 +29,8 @@ public class User extends BaseTimeEntity {
private Long id;

@ManyToOne(fetch = LAZY)
@JoinColumn(name = "dongnae_id", nullable = false)
@JoinColumn(name = "dongnae_id")
@Nullable
private Dongnae dongnae;

@Column(nullable = false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@

import com.umc.DongnaeFriend.domain.user.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

Optional<User> findById(Long id);

Optional<User> findByRefreshToken(String refresh_token);

Optional<User> findByKakaoId(Long id);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.umc.DongnaeFriend.domain.user.service;


import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.HashMap;

public interface KakaoService {


@SuppressWarnings("unchecked")
HashMap<String, Object> getUserInfo(String access_Token) throws IOException;
}


Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package com.umc.DongnaeFriend.domain.user.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class KakaoServiceimpl implements KakaoService {

// @Autowired
// public IACDao dao;

@SuppressWarnings("unchecked")
@Override
public HashMap<String, Object> getUserInfo(String access_Token) throws IOException {
// 클라이언트 요청 정보
HashMap<String, Object> userInfo = new HashMap<String, Object>();


//------kakao GET 요청------
String reqURL = "https://kapi.kakao.com/v2/user/me";
URL url = new URL(reqURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + access_Token);

int responseCode = conn.getResponseCode();
System.out.println("responseCode : " + responseCode);

BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String line = "";
String result = "";

while ((line = br.readLine()) != null) {
result += line;
}
System.out.println("response body : " + result);
System.out.println("result type" + result.getClass().getName()); // java.lang.String

// jackson objectmapper 객체 생성
ObjectMapper objectMapper = new ObjectMapper();
// JSON String -> Map
Map<String, Object> jsonMap = objectMapper.readValue(result, new TypeReference<Map<String, Object>>() {
});


System.out.println(jsonMap.get("properties"));

Long id = (Long) jsonMap.get("id");
Map<String, Object> properties = (Map<String, Object>) jsonMap.get("properties");
Map<String, Object> kakao_account = (Map<String, Object>) jsonMap.get("kakao_account");
Map<String, Object> profile = (Map<String, Object>) kakao_account.get("profile");

log.info("profile : " + profile.toString());
log.info("kakao_acount : " + kakao_account.toString());

String nickname = properties.get("nickname").toString();
String profileImage = properties.get("profile_image").toString();
String email = kakao_account.get("email").toString();

userInfo.put("id", id);
userInfo.put("nickname", nickname);
userInfo.put("profileImage", profileImage);
userInfo.put("email", email);


return userInfo;
}

}
Loading

0 comments on commit 430d5b1

Please sign in to comment.