inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

스프링부트 시큐리티 & JWT 강의

마지막 강의 질문드립니다.

616

yoii

작성한 질문수 4

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가 아닌 저렇게 권한설정을 해주었는데요

잘못된 부분이 있는지 문의드립니다.

 

 

 

jwt spring-security Spring Security spring

답변 1

1

최주호

ROLE_ 를 hasAnyRole에서 삭제해주세요. 이제 deprecate 되었습니다.

뒤에 MANAGER, USER 이런것만 추가하시면 됩니다.

JWT를 구현한 다음 이 API를 호출해서 사용하는 것은 프론트엔드 쪽에서 하는 역할인가요?

0

99

1

Jwt쓰면 스프링시큐리티는 필수적으로 사용해야하나요?

0

402

1

13:23 system.out 출력문이 다르게 나옵니다.

0

132

1

수료증 문의

0

230

2

9분대에 질문이 있습니다 !

0

117

1

password 비교를 하지 않았는데 어떻게 인증이 통과된 건가요?

0

322

1

이전 강의 참고하라는 말씀

0

253

1

강의 실습하다가 막히는 분들 참고(2024년8월 기준)

2

1119

2

구글 소셜 로그인 302

0

202

1

오류 문의 _ org.springframework.orm.jpa.JpaSystemException: could not deserialize

1

586

1

[자바] 시큐리티 Config 참고

13

954

1

이론강의

0

282

1

SpringSecurity JWT 로그인 URL 2개 설정하는 방법

0

490

1

2024.06기준) 최근 SecurityConfig 설정 문의

0

922

3

구글 로그인시 authentication이 null 값이라고 에러가 발생합니다.

0

681

2

특정 url필터 거는 방법 이슈

0

423

1

강사님께서 말씀하시는 시큐리티세션이 SecurityContext인가요?

0

280

1

25강 마지막 테스트에서 오류

1

1044

2

jwt를 저장하는 위치에 궁금한 점이 있습니다.

0

299

1

mustache를 사용하지 않고 thymeleaf를 사용하려고 하는데

0

700

1

세션 인증방식이 REST 원칙에 위배되는 건가요?

0

343

1

jwt와 실제데이터의 관계

1

248

1

jwt 와 세션ID의 관계

1

314

1

SecurityConfig에서 세션 설정, 인가 설정

0

424

1