【问题标题】:Spring Security getprincipal() method returns string (Username) in place of class UserDetailsSpring Security getprincipal() 方法返回字符串(用户名)代替类 UserDetails
【发布时间】:2019-08-25 19:51:35
【问题描述】:

我们正在使用带有 JWT 令牌的 Spring-boot 2.0.5

SecurityContextHolder.getContext().getAuthentication().getPrincipal() 返回 String (Username) 代替 CustomUserDetails 对象,该对象仅在 WAR 文件中实现 UserDetails 类。

这个问题只是偶尔重复,大多数时候代码运行良好

下面提到的是我们使用的唯一自定义过滤器,它在 FilterSecurityInterceptor Filter 之后调用

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    CustomHttpServletRequestWrapper request = new CustomHttpServletRequestWrapper((HttpServletRequest) req);
    if(request!=null && request.getHeader("Authorization")!=null && request.getHeader("Authorization").length()>7) {

        CustomUserDetails user = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}

它应该返回用户详细信息对象

【问题讨论】:

  • 这取决于配置,在我们的例子中,我们在 AuthorizationServerEndpointsConfigurer 中使用 DefaultUserAuthenticationConverter 并且它依赖于 UserDetailsS​​ervice 来获取 UserDetails 如果未设置您将获得一个字符串,即用户名而不是 UserDetail 对象。跨度>

标签: linux spring-boot jwt war spring-security-oauth2


【解决方案1】:

在我们的例子中,有两个同名的 Bean 导致了问题

【讨论】:

    【解决方案2】:

    没有足够的信息为您提供任何答案,很高兴知道:

    • SecurityContextHolder.getContext().getAuthentication()返回什么实例?
    • 您拥有的安全过滤器列表是什么?您的自定义过滤器在哪里?
    • 什么时候会发生这种情况?你必须知道重现它的步骤

    【讨论】:

    • SecurityContextHolder.getContext().getAuthentication() 返回什么实例? -----它返回 SecurityContext 您拥有的安全过滤器列表是什么,您的自定义过滤器在哪里? -----自定义安全过滤器只是上面提到的过滤器-----它是在FilterSecurityInterceptor之后执行的,什么时候发生?您必须知道重现它的步骤 ----- 每当尝试调用授权端点时
    • re #1 SecurityContext 来自 getContext() 但 Authentication 的实例是什么?
    • re #2 你能分享一些你的自定义过滤器的逻辑吗?
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2018-05-28
    • 2016-02-19
    • 2012-02-21
    • 2016-04-27
    • 2017-10-17
    • 1970-01-01
    • 2011-07-12
    相关资源
    最近更新 更多