【问题标题】:Access authentication object when request does not pass Spring security chain请求未通过 Spring 安全链时访问身份验证对象
【发布时间】:2017-03-15 14:30:09
【问题描述】:

我想要实现的是一个不安全的页面(例如 /index),但是在经过身份验证后,它应该可以访问身份验证对象以显示已登录的用户。

根据Spring文档,认证对象在不通过安全过滤链时是不可用的:

如果要在请求期间使用 SecurityContext 内容的内容,则它必须通过安全过滤器链。否则 SecurityContextHolder 将不会被填充并且内容将为空。

但是要禁用页面安全,安全过滤器被禁用:

<http pattern="/index" security="none"/>

类似于 filters=”none”,这也将完全禁用该请求路径的安全过滤器链 - 因此当应用程序处理请求时,Spring Security 功能将不可用。

我也不能使用&lt;intercept-url pattern="/index" access="permitAll" /&gt;,因为这会授予所有经过身份验证的用户权限。因为AbstractSecurityInterceptor会在没有找到认证对象时抛出AuthenticationCredentialsNotFoundException

作为 Spring Security 的新手,我如何构建一个可以访问 SecurityContext 的非安全页面? (使用带有 XML 配置的 Spring Security 3.2.9)

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    您可以使用AnonymousAuthenticationFilter,当没有用户登录时,它会创建一个AnonymousAuthenticationToken 实例并将其分配给SecurityContextHolder.getContext().setAuthentication()。因此您不会得到AuthenticationCredentialsNotFoundException,并且可以执行一个简单的instanceof 操作来检查用户是否已登录或匿名。

    <bean id="anonymousAuthFilter"
          class="org.springframework.security.web.authentication.AnonymousAuthenticationFilter">
        <property name="key" value="anonymousUser"/>
        <property name="userAttribute" value="anonymousUser,ROLE_ANONYMOUS"/>
    </bean>
    
    <http pattern="/**">
        <intercept-url pattern="/index" access="permitAll"/>
        <custom-filter ref="anonymousAuthFilter" position="ANONYMOUS_FILTER" />
    </http>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 2021-12-27
      • 2021-08-04
      • 1970-01-01
      • 2020-10-17
      • 2019-02-21
      • 2016-12-25
      相关资源
      最近更新 更多