spring-security 为什么@预授权主体是字符串而不是UserDetails?

kiz8lqtg  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(186)

我有一个用@PreAuthorize注解的方法,它使用自定义bean

@PreAuthorize("@preAuthUtils.test(authentication)")
public void method(){
    ...
}

该bean什么也不做,只是输出auth和user(principle)

@Component(value = "preAuthUtils")
public class PreAuthUtils {
        public boolean test(UsernamePasswordAuthenticationToken x) {
                System.out.println("type: " + x.getClass().getSimpleName());
                System.out.println("string: " + x.toString());
                final var user = x.getPrincipal();
                System.out.println("type: " + user.getClass().getSimpleName());
                System.out.println("string: " + user.toString());
                return true;
        }
}

输出(请求后)

type: UsernamePasswordAuthenticationToken
string: UsernamePasswordAuthenticationToken [Principal=johndoe, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null], Granted Authorities=[ROLE_USER, ROLE_CUSTOMER]]

type: String
string: johndoe

问题是为什么用户的类型是String?而不是实现UserDetails的自定义“DefaultUserDetails”类?
因为我需要得到用户的id和信息来决定是否对用户进行身份验证或限制,我花了6个小时,我只想哭

olqngx59

olqngx591#

我终于弄明白了。
这一切都是由于我的JWT过滤器实际上验证了用户...
这里的主体是userDetails(IN WAS STRING ..)

final var authentication = new UsernamePasswordAuthenticationToken(principal, null, authorities);

                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(context));
                SecurityContextHolder.getContext().setAuthentication(authentication);

相关问题