4

我有一个现有的 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 参考和其他各种文章,我知道我需要使用 aRequestHeaderAuthenticationFilter并将其注入过滤器链以从请求标头中获取用户名。

筛选:

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 像这样失败有什么原因吗?

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

4

1 回答 1

1

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

添加此注释解决了问题

于 2015-01-20T22:24:13.063 回答