inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

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

JWT 실습 마지막 오류

343

컴공과

작성한 질문수 17

0

강의 너무나 잘 들었습니다. 

JWT 인증 마지막까지 수업을 듣고 user, manager, admin으로 api 요청시 강의와 달리

권한별로 api 접근이 정상 동작하지 않습니다.

강의를 그대로 따라하였으며 회원가입, 로그인하여 토큰 발급까지는 정상 동작합니다만

api 요청시 권한별로 페이지 이동이 되지 않습니다. jwt 관련 git 주소가 없어 추가 확인이 안되어 문의 드립니다.

 

"27장 따라하는 중입니다. Controller를 안타는듯 합니다." 질문과 동일 내용으로 보여집니다.

 

 


JwtAuthorizationFilter,
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
System.out.println("successfulAuthentication 실행됨 : 인증이 완료되었다는 뜻임.");

PrincipalDetails principalDetails = (PrincipalDetails) authResult.getPrincipal();

//Hash 암호방식
String jwtToken = JWT.create()
.withSubject("토큰")
.withExpiresAt(new Date(System.currentTimeMillis()+(JwtProperties.EXPIRATION_TIME)))
.withClaim("id", principalDetails.getUser().getId())
.withClaim("username", principalDetails.getUser().getUsername())
.sign(Algorithm.HMAC512(JwtProperties.SECRET));

// super.successfulAuthentication(request, response, chain, authResult);
response.addHeader(JwtProperties.HEADER_STRING, JwtProperties.TOKEN_PREFIX + jwtToken);

}

SecurityConfig
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(corsFilter) // 시큐리터 필터에 등록 인증(O), @CrossOrigin(인증x)
.formLogin().disable() // form login disable
.httpBasic().disable() //
.addFilter(new JwtAuthenticationFilter(authenticationManager())) // ID, PW 체크, 파라미터 : AuthenticationManager
.addFilter(new JwtAuthorizationFilter(authenticationManager(), userRepository))
.authorizeRequests()
.antMatchers("/api/v1/user/**")
.access("hasRole('ROLE_USER') or hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')")
.antMatchers("/api/v1/manager/**")
.access("hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')")
.antMatchers("/api/v1/admin/**")
.access("hasRole('ROLE_ADMIN')")
.anyRequest().permitAll();

RestApiController
// user, manager, admin 권한 접근 가능
@GetMapping("/api/v1/user")
public String user() {
return "user";
}

// manager, admin 권한 접근 가능
@GetMapping("/api/v1/manager")
public String manager() {
return "manager";
}

// admin 권한 접근 가능
@GetMapping("/api/v1/admin")
public String admin() {
return "admin";
}

jwt Spring Security spring

답변 1

0

최주호

https://github.com/codingspecialist/Springboot-Security-JWT-Easy

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

0

116

1

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

0

423

1

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

0

137

1

수료증 문의

0

252

2

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

0

129

1

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

0

327

1

이전 강의 참고하라는 말씀

0

258

1

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

2

1131

2

구글 소셜 로그인 302

0

208

1

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

1

592

1

[자바] 시큐리티 Config 참고

13

960

1

이론강의

0

286

1

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

0

501

1

2024.06기준) 최근 SecurityConfig 설정 문의

0

943

3

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

0

697

2

특정 url필터 거는 방법 이슈

0

433

1

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

0

282

1

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

1

1052

2

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

0

306

1

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

0

705

1

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

0

346

1

jwt와 실제데이터의 관계

1

251

1

jwt 와 세션ID의 관계

1

318

1

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

0

427

1