-
카테고리
-
세부 분야
백엔드
-
해결 여부
미해결
마지막 강의 질문드립니다.
23.02.22 23:35 작성 조회수 449
0
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
// 안 지우면 응답을 한번하고 아래서 두번하게 됨 오류가 됨
// super.doFilterInternal(request, response, chain);
System.out.println("인증이나 권한이 필요한 주소 요청이 됨 ");
String jwtHeader = request.getHeader("Authorization");
System.out.println("JWT HEADER :: {} " + jwtHeader);
// JWT 토큰을 검증해서 정상적인 사용자인지 확인하기
if (jwtHeader == null || !jwtHeader.startsWith("Bearer")) {
chain.doFilter(request, response);
// 밑에 진행이 안되게
return;
}
String token = request.getHeader("Authorization").replace("Bearer ", "");
String username = JWT.require(Algorithm.HMAC512("cos")).build().verify(token).getClaim("username").asString();
// 서명이 정상적으로 됨
if (username != null) {
User userEntity = userRepository.findByUsername(username);
PrincipalDetails principalDetails = new PrincipalDetails(userEntity);
// 임의의 authentication 만들기 username 이 null 이 아니라는게 인증이 된거임
// jwt 토큰 서명을 통해서 서명이 정상이면 Authentication 객체를 만들어준다
Authentication authentication = new UsernamePasswordAuthenticationToken(principalDetails, null, principalDetails.getAuthorities());
// 시큐리티 저장할 수 있는 세션 공간
//강제로 시큐리티의 세션에 접근하여 Authentication 객체를 저장
SecurityContextHolder.getContext().setAuthentication(authentication);
}
chain.doFilter(request, response);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
// 내 서버는 STATELESS
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilterBefore(new JwtFilter(), SecurityContextHolderFilter.class)
.addFilter(corsFilter) // CrossOrigin(인증X) 시큐리티필터에 등록인증(O)
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
.addFilter(new JwtAuthorizationFilter(authenticationManager(), userRepository))
// CrossOrigin 정책 안쓰고 모든 요청 허용
.formLogin().disable() // 폼로그인 사용 안함
.httpBasic().disable() // http 로그인 방식 안쓰겠다
.authorizeHttpRequests(auth ->
auth.requestMatchers("/api/v1/user/**").hasAnyRole("ROLE_USER", "ROLE_MANAGER", "ROLE_ADMIN")
.requestMatchers("/api/v1/manager/**").hasAnyRole("ROLE_MANAGER", "ROLE_ADMIN")
.requestMatchers("/api/v1/admin/**").hasRole("ROLE_ADMIN")
.anyRequest().permitAll()
);
return http.build();
}
마지막 강의 실습을 하는데요
디버깅 하면 유저 정보 정보 및 권한이 잘 조회되고 있지만
403 에러가 발생하고 있습니다.
SecuriyConfig에는 deprecated 를 이유로 antMatchers가 아닌 저렇게 권한설정을 해주었는데요
잘못된 부분이 있는지 문의드립니다.
답변을 작성해보세요.
1
최주호
지식공유자2023.02.27
ROLE_ 를 hasAnyRole에서 삭제해주세요. 이제 deprecate 되었습니다.
뒤에 MANAGER, USER 이런것만 추가하시면 됩니다.
답변 1