caffeine-library / pro-spring-5

🌱 전문가를 위한 스프링5를 읽는 스터디
5 stars 0 forks source link

[question] 스프링 MVC 프로젝트 코드 분석 #99

Closed JasonYoo1995 closed 2 years ago

JasonYoo1995 commented 2 years ago

질문

MVC 기술과 관련 기술들이 들어간 스프링 프로젝트 코드를 참고해보고 분석해봅시다

상세 내용

https://github.com/JasonYoo1995/fasting-date-count 본 코드는 스프링에 막 입문하신 분께서 연습 삼아 작성한 코드이기에 Best Practice는 아니라고 하시지만, 제가 봤을 때는 참고하기 좋은 부분이 많아 보여서 큰 도움이 될 것 같아 링크를 가져와 봤습니다!

연관 챕터

93

JasonYoo1995 commented 2 years ago

스프링 시큐리티

@RequiredArgsConstructor
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final CustomOAuth2UserService customOAuth2UserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .headers().frameOptions().disable() // h2-console 화면을 사용하기 위함
                .and()
                    .authorizeRequests() // endpoint별 권한 관리 시작점
                    .antMatchers("/", "/css/**", "/images/**", "/js/**", "/h2-console/**", "/deploy").permitAll() // antMatchers를 통해 권한 관리 대상 지정, permitAll: 전체 열람 가능
                    .anyRequest().authenticated() // 나머지 요청에 대해서는 로그인한 사용자만 허용
                .and()
                    .logout()
                        .logoutSuccessUrl("/") // 로그아웃 성공 시 이동 경로
                        .invalidateHttpSession(true) // 로그아웃 이후 세션 전체 삭제
                        .deleteCookies("JSESSIONID") // 쿠키도 삭제
                .and()
                    .oauth2Login() // 로그인 기능에 대한 진입점
                        .userInfoEndpoint() // 로그인 성공 이후 사용자 정보를 가져올 때 설정
                            .userService(customOAuth2UserService) // 로그인 성공 시 조치를 진행할 서비스 구현체
                            .and()
                        .defaultSuccessUrl("/food", true);
    }
}

에러 처리

review-save.mustache에서 '등록' 버튼을 통해 리뷰 등록을 요청하면 main.js의 saveReview 함수가 실행되면서 /api/food/{foodId}/reviews URL의 ajax POST 요청이 일어나는데 해당 URL은 ReviewApiController.save()에 매핑되어 있으며 ReviewApiController.save()는 ReviewService.save()를 호출한다 ReviewService.save()안에 있는 validateUserAuthority()의 내용 중
throw new ServiceException(HttpStatus.FORBIDDEN, ErrorCode.ACCESS_DENIED);가 있는데 ErrorCode.ACCESS_DENIED는 ErrorCode.java에 정의돼있다. 이때, validateUserAuthority()에서 에러가 발생하면, 에러가 상위 메서드로 전파되다가 ReviewApiController.save()까지 전파되면 최종적으로 GlobalExceptionHandler가 에러를 처리한다 그럼 Client에게 에러 정보가 응답되면서 main.js의 saveReview에 있는 error 콜백 함수가 실행된다.

세션 조회

참고 레포