Skip to content

Document what is the difference between new requestMatchers and securityMatchers #12950

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
craph opened this issue Mar 31, 2023 · 12 comments
Closed
Assignees
Labels
in: docs An issue in Documentation or samples status: duplicate A duplicate of another issue type: enhancement A general enhancement

Comments

@craph
Copy link

craph commented Mar 31, 2023

Expected Behavior

Is it possible to have a more detailled documentation about the difference betwenn new requestMatchers and securityMatchers ?

Current Behavior

After reading this : https://docs.spring.io/spring-security/reference/5.8/migration/servlet/config.html#use-new-security-matchers

there is :

In Spring Security 5.8, the antMatchers, mvcMatchers, and regexMatchers methods were deprecated in favor of new requestMatchers methods.

and

In Spring Security 5.8, the antMatchers, mvcMatchers and requestMatchers methods from HttpSecurity were deprecated in favor of new securityMatchers methods.

It's a little confusing.

Is there any documentation that explains the difference with examples and may be samples with an equivalent with xml configuration to have another view ?

By reading the current documentation, I don't understand when to use securityMatchers

How securityMatchers is different from requestMatchers ?

Context

Thank you very much for your help.
Best regards,

@craph craph added status: waiting-for-triage An issue we've not yet triaged type: enhancement A general enhancement labels Mar 31, 2023
@pnedonosko
Copy link

+1 to the question: the new securityMatcher/securityMatchers methods create confusion when read the doc. It's not obvious when to use what: securityMatcher or authorizeHttpRequests or both, what effects in the result? Especially knowing the authorizeHttpRequests is a new thing instead of deprecated authorizeRequests, when a newbie look at the sample from 6.0.3 doc (and many examples in internet but for older versions), use of the the both with comments below may mislead seriously:

@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http
			.securityMatcher("/api/**")                            <<< 1
			.authorizeHttpRequests(authorize -> authorize
				.requestMatchers("/user/**").hasRole("USER")       <<< 2
				.requestMatchers("/admin/**").hasRole("ADMIN")     <<< 3
				.anyRequest().authenticated()                      
			)
			.formLogin(withDefaults());
		return http.build();
	}
  1. Configure HttpSecurity to only be applied to URLs that start with /api/
  2. Allow access to URLs that start with /user/ to users with the USER role
  3. Allow access to URLs that start with /admin/ to users with the ADMIN role

After finding similar code samples with roles/authorities but without securityMatcher used, it messes things and creates more questions instead of understanding. For sure such answers can be found in the Spring Security code, but it's not a quick way and often shifts the focus.

But would the sample code be like:

      .securityMatcher("/api/**")
      .authorizeHttpRequests(authorize -> authorize
				.requestMatchers("/api/user/**").hasRole("USER")       
				.requestMatchers("/api/admin/**").hasRole("ADMIN")     
				.anyRequest().authenticated()                      
			)

with later description something like:
Configure HttpSecurity for only URLs starting with /api and next customizing authorized access for /api/user to only USER and /api/admin to ADMIN roles, we leave all other URLs not secured (without authentication and authorization).
Note, that several URL patterns can be supplied to securityMatcher for applying security on all them.

Thank you.

@ghusta
Copy link
Contributor

ghusta commented May 4, 2023

A good example on how to use the new securityMatcher(...) can be found in this video by Dan Vega 👍

🎬 https://www.youtube.com/watch?v=PczgM2L3w60

See also : https://docs.spring.io/spring-security/reference/5.8/servlet/configuration/java.html#_multiple_httpsecurity

@pnedonosko
Copy link

@ghusta a good example, thank you Guillaume 👍

@ASDasd341
Copy link

  1. request Matchers is a method provided by the Http Security class in Spring Security. It is used to match incoming requests based on URL patterns and HTTP methods. it is typically used in the configure(Http Security http) method of a custom "WebSecurityConfigurerAdapter.requestMatchers" method accepts one or more Request Matcher instances, which determine which requests should be matched by the security rules. A Request Matcher can be created using AntPathRequestMatcher.
  2.  protected void configure(Http Security http) throws Exception {
      http
     .authorizeRequests()
         .requestMatchers(new AntPathRequestMatcher("/public/**")).permitAll()
         .requestMatchers(new RegexRequestMatcher("/admin/.*", "GET")).hasRole("ADMIN")
         .anyRequest().authenticated()
     .and()
     .formLogin()
     .and()
     .httpBasic();
    

}
3. securityMatchers is a method provided by the RequestMatcherConfigurer class in Spring Security. It is used in combination with antMatchers, regexMatchers, and other similar methods to configure URL pattern matching for security rules. securityMatchers method accepts one or more RequestMatcher instances along with an additional RequestMatcher for the condition.
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.securityMatchers(new AntPathRequestMatcher("/api/**"),
new HeadersRequestMatcher("X-Requested-With", "XMLHttpRequest")).authenticated()
.anyRequest().permitAll()
.and()
.formLogin()
.and()
.httpBasic();
}

@onomesotu
Copy link

This part of the document describes the usages and differences quite clearly:
https://docs.spring.io/spring-security/reference/5.8/servlet/authorization/authorize-http-requests.html#_request_matchers

@sjohnr sjohnr self-assigned this Jun 6, 2024
@sjohnr sjohnr added in: docs An issue in Documentation or samples and removed status: waiting-for-triage An issue we've not yet triaged labels Jun 6, 2024
@sjohnr
Copy link
Contributor

sjohnr commented Jun 6, 2024

@pnedonosko

But would the sample code be like:

      .securityMatcher("/api/**")
      .authorizeHttpRequests(authorize -> authorize
				.requestMatchers("/api/user/**").hasRole("USER")       
				.requestMatchers("/api/admin/**").hasRole("ADMIN")     
				.anyRequest().authenticated()                      
			)

I think you are correct that this is a typo in the docs and it should be as you corrected it to be. Would you mind opening a new issue or pull request to correct the example here?


@craph @pnedonosko @ghusta @onomesotu @ASDasd341 thanks so much for the feedback!

In addition to this answer:

This part of the document describes the usages and differences quite clearly: https://docs.spring.io/spring-security/reference/5.8/servlet/authorization/authorize-http-requests.html#_request_matchers

I've also recently enhanced the Configuration > Java and Configuration > Kotlin chapters of the reference.

Regarding "What is the difference between new requestMatchers and securityMatchers?" based on the opening comment:

By reading the current documentation, I don't understand when to use securityMatchers

I feel like the docs update now answers this question in the section Choosing securityMatcher or requestMatchers. As such, I'm going to close this issue as a duplicate of gh-14419 just for book-keeping since that issue is already resolved.

If anyone has additional feedback please don't hesitate to comment here or open a new issue and we can keep improving the docs!

@sjohnr sjohnr closed this as completed Jun 6, 2024
@sjohnr sjohnr added the status: duplicate A duplicate of another issue label Jun 6, 2024
@dsuepke-swisscom
Copy link

Hello, I would like to point out that even with the new documentation the difference between requestMatchers and securityMatchers is still completely lost on me (and others). I googled for this and all I found were questions from others what the difference is with no answers, since apparently (almost) no one seems to understand.

This notion - imho - is very much untrue:

This part of the document describes the usages and differences quite clearly: https://docs.spring.io/spring-security/reference/5.8/servlet/authorization/authorize-http-requests.html#_request_matchers

@sjohnr
Copy link
Contributor

sjohnr commented Jul 17, 2024

@dsuepke-swisscom thank you so much for your feedback! I am sorry you still do not have a good grasp on this concept. We are actively taking in feedback such as this and working hard on ways to improve Spring Security and make it easier for everyone. We don't yet know what that will look like, but please know that it is a priority. In the meantime, is there anything specific you feel can be done to help improve the situation?

I've also recently enhanced the Configuration > Java and Configuration > Kotlin chapters of the reference.

I've tried to outline a set of examples in the above links for 6.4 (starting from Multiple HttpSecurity Instances) that demonstrate the difference. Can you help me improve them?

@dsuepke-swisscom
Copy link

dsuepke-swisscom commented Jul 19, 2024

Hi @sjohnr, thanks for the quick reply and help. I will try to provide some feedback for improvements. The link you sent is actually more clear to me, don't have anything to add on those atm, good work. Going back to https://docs.spring.io/spring-security/reference/5.8/servlet/authorization/authorize-http-requests.html#_request_matchers, some of the question I have:

It seems like "securityMatcher" for /api/** is the initial filter, if that doesn't match then the rest of this chain is ignored. But then why are there requestMatchers for /user/**? Those could never be applied, right? Or am i getting the premise wrong what securityMatcher does?

I find the name "securityMatcher" confusing. A requestMatcher is matchin a request. What is a securityMatcher matching, security? - probably the HttpSecurity object is meant, but that seem off to me. More appropriate (again, only if I get it right, which I'm not sure of) would be something like "filterChainMatcher".

@sjohnr
Copy link
Contributor

sjohnr commented Jul 29, 2024

@dsuepke-swisscom,

The link you sent is actually more clear to me, don't have anything to add on those atm, good work.

Thank you very much! I'm glad it is more clear. Let me know if you have suggestions at any point.

It seems like "securityMatcher" for /api/** is the initial filter, if that doesn't match then the rest of this chain is ignored. But then why are there requestMatchers for /user/**? Those could never be applied, right?

You are correct, that example does not appear to be correct. It should be something like requestMatchers("/api/user/**")... or something similar (depending on what the example was trying to convey, which is not 100% clear because of the mistake).

I find the name "securityMatcher" confusing. A requestMatcher is matchin a request. What is a securityMatcher matching, security? - probably the HttpSecurity object is meant, but that seem off to me. More appropriate (again, only if I get it right, which I'm not sure of) would be something like "filterChainMatcher".

Your understanding is correct, and filterChainMatcher would be a very accurate name. Sadly, I don't know the history of the naming of the method securityMatcher, but regardless your feedback is very valuable that this name is confusing. I will take that feedback to the team. We're working on gathering such feedback and folding it into an effort to improve Spring Security, so thanks for providing it!

@OksiBlack
Copy link

Example really are confusing...

@rodrigosomoza
Copy link

Novembre 2024 and the security matcher documentation is still not clear... From the doc:

--> 1. Configure HttpSecurity to ONLY be applied to URLs that start with /api/ .
While in point 2 and 3 : Allow access to URLs that START with /user/ to users with the USER role.

Saw some where that the securityMatcher is used to specify a scope where the rules will be applied. I will be very happy if someone can bring more clarifications, if there might be any change or improvement regarding this section.
Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
in: docs An issue in Documentation or samples status: duplicate A duplicate of another issue type: enhancement A general enhancement
Projects
None yet
Development

No branches or pull requests

9 participants