【问题标题】:Spring requestMatchers, antMatchers and authorizeRequests usageSpring requestMatchers、antMatchers 和 authorizeRequests 使用
【发布时间】:2019-05-26 10:35:15
【问题描述】:

我正在尝试了解 requestMatchers、antMatchers 和 authorizeRequests 的用途。

  1. 如果我们只使用 requestMatchers 会发生什么?

    http.requestMatchers();

  2. 如果使用 requestMatchers 和 antMatchers 会发生什么?

    http.requestMatchers().antMatchers("/", "/login");

  3. 如果使用 requestMatchers、antMatchers 和 authorizeRequests 会发生什么?

    http.requestMatchers().antMatchers("/", "/login").and().authorizeRequests().anyRequest().authenticated();

因此,如果在情况 3 中 requestMatchers() 为 '/login' 和 '/' 产生异常,因此它们不会被验证,或者这是否意味着它们也需要验证。

将 requestMatchers() 放在 authorizeRequests() 之前的整个过程让人感到困惑。需要知道它们到底在做什么以及组合 antmacthers 会做什么。

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    如果我们只使用 requestMatchers 会发生什么? http.requestMatchers();

    这只是一个无用的方法调用。英文是这样写的:对于所有传入的http请求,我想根据这个匹配器列表过滤它们,当然没有匹配器列表,所以它什么都不做。

    如果使用 requestMatchers 和 antMatchers 会发生什么?

    http.requestMatchers().antMatchers("/", "/login");

    又一个无用的方法调用。在英语中,它读作:对于所有传入的 http 请求,根据匹配器列表、“/”和“/login”过滤它们,但你没有告诉它要做什么,所以它什么也不做。

    如果使用 requestMatchers、antMatchers 和 授权请求?

    http.requestMatchers().antMatchers("/", "/login").and().authorizeRequests().anyRequest().authenticated();

    这样好多了。在英语中,它读作:对于所有传入的 http 请求,我想根据这个匹配器列表过滤它们,即“/”和“/login”,并且我希望它们只能由经过身份验证的用户访问.

    如果您使用的是 Spring Security,那么 Spring 将检查其 SecurityContext(存储在 ThreadLocal 变量中)以找出是否存在包含 PrincipalAuthentication 对象(经过身份验证的用户,其中通常是UserDetails 对象的一个​​实例)。如果有,则允许请求继续,如果没有,则会收到丑陋的 403,禁止。

    所以如果 3 确实 requestMatchers() 为 '/login' 和 '/' 所以他们不会被认证或者这是否意味着他们也需要 身份验证。

    如上所述。

    问题是通过 Spring Security 的 Spring Boot 对我们来说变得如此简单,只需几行配置即可开始使用坚实的安全基础。只需尝试一下,大约一个小时左右,您就可以开始生产了。

    祝你好运!

    【讨论】:

      【解决方案2】:
      1. 毫无意义 2.添加一些ant模式的路径,用于与传入请求中的url匹配,如果匹配,将选择具有这些路径的过滤器链来过滤该传入请求。 3.authorizeRequests().anyRequest().authenticated() 表示通过所选过滤器链验证所有传入请求。 总之,requestMatchers 用于设置路径以匹配您想要的请求,authorizeRequests 用于根据您通过诸如 antMatchers("XXX").permitAll() 之类的方法设置的规则对这些请求进行身份验证。

      【讨论】:

        猜你喜欢
        • 2016-11-26
        • 2018-03-27
        • 2020-04-16
        • 2013-12-30
        • 2019-02-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-31
        • 1970-01-01
        相关资源
        最近更新 更多