【问题标题】:Get access to HttpServletRequest within a custom AuthenticationProvider在自定义 AuthenticationProvider 中访问 HttpServletRequest
【发布时间】:2020-04-23 03:11:19
【问题描述】:

如何在自定义 AuthenticationProvider 中访问 HttpServletRequest。我试过这样做

RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
String username = (String) httpReq.getAttribute("j_username");

RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest httpReq = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();

String username = (String) httpReq.getAttribute("j_username");

我的用户名为空

RequestContextHolder.getRequestAttributes(); 返回null

我想引用 requestcontext,将其传入,或者让 Spring 发挥它的魔力,以便我可以引用它。

我还在 web.xml 中提供 RequestContextListener

  <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>

我已经搜索了安全论坛,但仍然没有找到任何东西。

提前致谢。

【问题讨论】:

  • 这些凭据不应该包含在 Authentication 对象中吗? static.springsource.org/spring-security/site/docs/3.0.x/apidocs/…
  • Dardo 是正确的。我认为您可能应该查看一些基本示例并阅读一些文档,然后更详细地解释您要实现的目标,因为我想不出尝试以这种方式访问​​用户名的正当理由。
  • 凭据确实在 Authentication 对象中。但是,我也在寻找解决方案。我也需要访问该请求,但出于另一个原因。在我的应用程序中,URL 在身份验证中起作用。关于如何在本课程中获得它的任何想法?

标签: spring-mvc spring-security


【解决方案1】:

我刚刚将侦听器添加到我的 web.xml 中,并且 RequestContextHolder.getRequestAttributes() 返回 RequestAttributes 而不是 null。

<listener>
  <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

如果你想自定义登录表单,为什么不扩展这个过滤器:org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter

【讨论】:

    【解决方案2】:

    使用 request.getParameter("j_username");而不是 request.getAttribute("j_username");

    它对我有用。看看对你有没有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      • 2016-03-09
      • 1970-01-01
      • 2012-01-28
      • 2016-12-07
      • 2012-07-07
      • 2017-05-27
      相关资源
      最近更新 更多