【问题标题】:Spring Security HeaderPreAuthentication Principal Not Resolved from @AuthenticationPrincipalSpring Security HeaderPreAuthentication Principal 未从 @AuthenticationPrincipal 解析
【发布时间】:2015-03-11 16:54:12
【问题描述】:

我有一个现有的 Spring Boot 应用程序,该应用程序对由第三方身份验证服务处理的 Web 应用程序进行身份验证。与 SiteMinder 一样,第 3 方服务将标头注入 HTTP 请求,例如 USER_HEADER。我的任务是配置现有应用程序以提取此 HTTP 标头并通过 Spring Security @AuthenticatedPrincipal 注释将生成的 Auth 对象提供给 MVC 层的控制器。

如前所述,项目是一个 Spring Boot 应用程序,版本 1.1.9.RELEASE,带有 Java 8。

(下面显示的代码来自一个镜像功能的测试项目)

请注意,此应用程序仅是 Java Config。不允许使用 XML(我的领导授权)

通过挖掘Spring Security reference 和其他各种文章,我知道我需要使用RequestHeaderAuthenticationFilter 并将其注入过滤器链以从请求标头中获取用户名。

过滤器:

public class HeaderAuthenticationFilter extends RequestHeaderAuthenticationFilter {
    private static final Logger logger = LoggerFactory.getLogger(HeaderAuthenticationFilter.class);
    private final String HEADER = "USER_HEADER";

    public HeaderAuthenticationFilter() {
        super();
        this.setPrincipalRequestHeader(HEADER);

        // This setting returns an HTTP 404 with no error message instead of an HTTP 500 with the "missing header" exception message
        this.setExceptionIfHeaderMissing(false);
    }

    @Override
    protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
        logger.debug("Authorizing URI: " + request.getRequestURI());

        try {
            return super.getPreAuthenticatedPrincipal(request);
        } catch(PreAuthenticatedCredentialsNotFoundException e) {
            logger.error("Could not find request header " + HEADER + " in request", e);
            return null;
        }
    }
}

如您所见,非常基本的过滤器。

使用我现在拥有的代码,用户从 HTTP 请求中提取,通过 PreAuthentication 过程进行,其中 PreAuthenticatedAuthenticationToken 由自定义 AuthenticationManager 创建,用户业务对象作为主体注入到令牌中,并且令牌最终分配给 SecurityContext : SecurityContextHolder.getContext().setAuthentication(principal);

但是,当我用@AuthenticationPrincipal User user 注释我的控制器方法时,返回的用户对象是一个空的用户对象。当我将方法参数更改为Authentication user 并显式调用user.getPrincipal() 时,我得到了用户对象就好了。 @AuthenticationPrincipal 这样失败有什么原因吗?

谢谢,如果需要更多详细信息,请告诉我!

【问题讨论】:

    标签: java spring spring-security spring-boot pre-authentication


    【解决方案1】:

    @AuthenticationPrincipal 没有解析的原因是因为我没有用@EnableWebMvcSecurity 注释我的 WebSecurityConfigurerAdapter 类

    添加此注释解决了问题

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 2016-07-13
      • 2019-04-14
      • 2015-10-22
      • 2016-03-05
      • 2020-12-02
      • 1970-01-01
      • 2016-07-12
      • 2014-01-02
      相关资源
      最近更新 更多