【问题标题】:How to allow anonymous user access from localhost only in Spring security?如何仅在 Spring 安全性中允许来自本地主机的匿名用户访问?
【发布时间】:2019-10-28 23:28:44
【问题描述】:

我只想允许来自 localhost 的特定 URL 模式的请求。到目前为止我试过这个:

<sec:intercept-url pattern="/blabla/**" access="hasIpAddress('127.0.0.1')" />

但这不起作用,我在日志输出中得到以下语句:

Access is denied (user is anonymous); redirecting to authentication entry point

所以我的问题是,我如何只允许来自本地主机的匿名用户访问?

【问题讨论】:

  • 尝试添加IP为&lt;sec:intercept-url pattern="/blabla/**" access="hasIpAddress('127.0.0.1:portnumber')" /&gt;的端口号

标签: java spring spring-security


【解决方案1】:

我最终使用了以下内容:

http.authorizeRequests()
// restrict all requests unless coming from localhost IP4 or IP6
.antMatchers("/**").access("hasIpAddress(\"127.0.0.1\") or hasIpAddress(\"::1\")")

我仅尝试使用hasIpAddress("127.0.0.1"),如果我将该 IP 放入浏览器 url,它可以正常工作,但它无法从 localhost 作为别名请求它。

【讨论】:

    【解决方案2】:

    是否可以在基于 XML 的配置中表达这种 and() 关系?

    根据此处https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html 的文档,下面应该可以工作。

    这里我们定义了应用程序的“blabla”区域(由 URL 模式定义)应该只对 IP 地址匹配 127.0.0.1 的匿名用户可用。

        <sec:intercept-url pattern="/blabla/**"
            access="isAnonymous() and hasIpAddress('127.0.0.1')"/>
    

    【讨论】:

    • 当我尝试使用 hasIpAddress('127.0.0.1') 时,它只允许从 IP 地址访问,但拒绝从 localhost 访问。我也通过添加它的 IP6 版本使其工作hasIpAddress('127.0.0.1') or hasIpAddress('::1')
    【解决方案3】:

    看看HttpSecurity::anonymous方法启用和提供匿名身份验证的AnonymousConfigurer&lt;H extends HttpSecurityBuilder&lt;H&gt;&gt;配置。

    在您的 Spring Security 配置类中,应该有一个覆盖方法:

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.and()
            .anonymous()...          // enables and configures the anonymous access
        .and()
            .authorizeRequests()...
    

    【讨论】:

    • 是否可以在基于 XML 的配置中表达这种and() 关系?
    猜你喜欢
    • 2012-03-05
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 2010-12-29
    相关资源
    最近更新 更多