Skip to content
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

Feat/authorize requests #27

Merged
merged 2 commits into from
Dec 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,16 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.and()

.authorizeRequests(auth -> auth // TODO : 회원, 비회원 권한 조정 필요
.antMatchers("/members/test").hasRole("USER")
.antMatchers("/h2/**").permitAll() // h2 데이터베이스 확인 가능하게
.antMatchers(HttpMethod.POST, "/questions").hasRole("USER") // 질문 작성
.antMatchers(HttpMethod.PATCH, "/questions/{question-id}").hasRole("USER") // 질문 수정
.antMatchers(HttpMethod.DELETE, "/questions/{question-id}").hasRole("USER") // 질문 삭제
.antMatchers(HttpMethod.POST, "/answers").hasRole("USER") // 답변 작성
.antMatchers(HttpMethod.PATCH, "/answers/{answer-id}").hasRole("USER") // 답변 수정
.antMatchers(HttpMethod.DELETE, "/answers/{answer-id}").hasRole("USER") // 답변 삭제
.antMatchers("/logout").hasRole("USER") // 로그아웃
.antMatchers("/members/{member-id}").hasRole("USER") // 마이페이지 확인, 회원정보 수정
.antMatchers(HttpMethod.POST, "/api/questions").hasRole("USER") // 질문 작성
.antMatchers(HttpMethod.PATCH, "/api/questions/{question-id}").hasRole("USER") // 질문 수정
.antMatchers(HttpMethod.DELETE, "/api/questions/{question-id}").hasRole("USER") // 질문 삭제
.antMatchers(HttpMethod.POST, "/api/answers").hasRole("USER") // 답변 작성
.antMatchers(HttpMethod.PATCH, "/api/answers/{answer-id}").hasRole("USER") // 답변 수정
.antMatchers(HttpMethod.DELETE, "/api/answers/{answer-id}").hasRole("USER") // 답변 삭제
.antMatchers("/api/auths/reissue").hasRole("USER") // 토큰 재발급
.antMatchers("/api/auths/logout").hasRole("USER") // 로그아웃
.antMatchers("/api/members/{member-id}").hasRole("USER") // 마이페이지 확인, 회원정보 수정

.anyRequest().permitAll())
.logout()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
import seb4141preproject.security.auth.dto.*;
import seb4141preproject.security.auth.service.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api/auths")
@RequiredArgsConstructor
Expand All @@ -20,9 +23,15 @@ public class AuthController {

// 회원가입 -> MemberService에서 처리.

@PostMapping("/login")
public ResponseEntity login(@RequestBody LoginDto loginDto) {
return new ResponseEntity<>(authService.login(loginDto), HttpStatus.OK);
@PostMapping("/login") // TODO : refresh Token 생성 후 cookie 저장?
public ResponseEntity login(@RequestBody LoginDto loginDto, HttpServletResponse response) {

// Cookie setting 로직 초안
TokenDto tokenDto = authService.login(loginDto);
// Cookie cookie = authService.createCookie(tokenDto);
// response.addCookie(cookie);

return new ResponseEntity<>(tokenDto, HttpStatus.OK);
}

@PostMapping("/reissue")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import seb4141preproject.security.auth.entity.*;
import seb4141preproject.security.auth.repository.RefreshTokenRepository;

import javax.servlet.http.Cookie;

@Service
@RequiredArgsConstructor
public class AuthService {
Expand All @@ -24,11 +26,10 @@ public class AuthService {
private final MemberMapper mapper;

public TokenDto login(LoginDto loginDto) {
// 1. Login ID/PW 를 기반으로 AuthenticationToken 생성
// 1. loginDto 기반 authenticationToken 생성 (toAuthentication 메소드 활용)
UsernamePasswordAuthenticationToken authenticationToken = loginDto.toAuthentication();

// 2. 실제로 검증 (사용자 비밀번호 체크) 이 이루어지는 부분
// authenticate 메서드가 실행이 될 때 CustomUserDetailsService 에서 만들었던 loadUserByUsername 메서드가 실행됨
// 2. token 검증
Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);

// 3. 인증 정보를 기반으로 JWT 토큰 생성
Expand Down Expand Up @@ -87,6 +88,14 @@ public void logout(TokenRequestDto tokenRequestDto) {
refreshTokenRepository.delete(refreshToken);
}

// refresh token Cookie 생성 로직
public Cookie createCookie(TokenDto tokenDto) {
Cookie cookie = new Cookie("refresh-token", tokenDto.getRefreshToken());
cookie.setHttpOnly(true);
cookie.setPath("/");
return cookie;
}

// 클래스 내부에서만 사용 가능한 토큰 생성하는 로직
private TokenDto createToken(Authentication authentication) {
String accessToken = jwtTokenizer.generateAccessToken(authentication);
Expand Down
14 changes: 7 additions & 7 deletions server/src/main/resources/import.sql
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
insert into member (member_id, name, email, password)
values
(1, '홍길동1', '[email protected]', '1111'),
(2, '홍길동2', '[email protected]', '2222'),
(3, '홍길동3', '[email protected]', '3333'),
(4, '홍길동4', '[email protected]', '4444'),
(5, '홍길동5', '[email protected]', '5555');
--insert into member (member_id, name, email, password)
--values
--(1, '홍길동1', '[email protected]', '1111'),
--(2, '홍길동2', '[email protected]', '2222'),
--(3, '홍길동3', '[email protected]', '3333'),
--(4, '홍길동4', '[email protected]', '4444'),
--(5, '홍길동5', '[email protected]', '5555');