readlog:: (Spring / Thymeleaf) SpringSecurity jwt :: error ::A granted authority textual representation is required

suragryen·2024년 4월 1일
0

Udemy-Spring

목록 보기
25/25

문제
1) 분명히 토큰이 발급 되었는데 JWTFilter 단계에서 tokennull이 뜸
2) Header에 Authorization을 추가해주었음에도 검증을 못함

계속 token null만 뜨다가
A granted authority textual representation is required
이라는 에러가 떠서 gpt한테 물어보니깐

getAuthorities() 메서드에서는 사용자의 권한(role)을 가져와서 SimpleGrantedAuthority 객체로 변환하여 authorities에 추가하고 있습니다. 그러나 이 오류는 SimpleGrantedAuthority 생성자에 전달되는 문자열 값이 null 또는 빈 문자열(empty string)이라는 것을 나타냅니다.

따라서 문제를 해결하기 위해서는 userEntity.getRole() 메서드에서 반환되는 값이 null이 아니고, 빈 문자열이 아닌지 확인해야 합니다. 또한 해당 값이 권한을 나타내는 문자열 형태로 제대로 설정되어 있는지도 확인해야 합니다.

결론: getRole()에서 값이 제대로 반환되지 않아서 생겼던 오류였다.
join할때 기본 값을 ROLE_USER를 기본값으로 줬었는데 제대로 가져오지 못한것일까? 하지만 Entiy에는 제대로 저장돼 있다 ;;

에러가 났던 코드

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    Set<GrantedAuthority> authorities = new HashSet<>();
    
    // 사용자가 가진 권한(role)을 가져와서 SimpleGrantedAuthority 객체로 변환하여 authorities에 추가합니다.
    authorities.add(new SimpleGrantedAuthority(userEntity.getRole()));

    // authorities를 반환합니다.
    return authorities;
}

해결

  @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> authorities = new HashSet<>();

        // 사용자의 권한(role)을 가져옵니다.
        String role = userEntity.getRole();

        // 권한(role)이 null이 아니고, 빈 문자열이 아닌 경우에만 authorities에 추가합니다.
        if (role != null && !role.isEmpty()) {
            // 권한(role)을 SimpleGrantedAuthority 객체로 변환하여 authorities에 추가합니다.
            authorities.add(new SimpleGrantedAuthority(role));
        } else {
            // 사용자의 권한(role)이 올바르게 설정되지 않은 경우, 기본 권한으로 설정할 수 있습니다.
            // 예를 들어, "ROLE_USER" 권한을 기본으로 설정합니다.
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        }

        // authorities를 반환합니다.
        return authorities;
    }

근본적인 해결은 아니고 원인을 파악했다
다음단계

  • MemberRepository에서 Role을 왜 못가져 오는지 체크
  • refresh 토큰에 대해 알아보기
  • 다른 페이지로 이동할때 검증 받은 토큰 사용하기
  • /login 페이지 세팅
profile
블로그 이사중 ☃︎

0개의 댓글

관련 채용 정보