spring Security 的requestMatchers方法

时间:2025-04-11 13:51:52

requestMatchers() 取得RequestMatcherConfigurer对象并配置允许过滤的路由;如requestMatchers().anyRequest()等同于().anyRequest().access(“permitAll”);如下面两个例子:

	@Override
	public void configure(HttpSecurity http) throws Exception {
		
//只允许路由由test开头的需要进行权限认证,其他的接口不需要权限认证;requestMatchers().anyRequest()即所有接口可以不进行认证;	
	http.requestMatchers().anyRequest().and().authorizeRequests().antMatchers("/test/*").authenticated();
 
	}
	@Override
	public void configure(HttpSecurity http) throws Exception {
		//只有以/test 开头的路由需要进行权限认证;其他路由不需要权限认证
		http.requestMatchers().antMatchers("/test/**").and().authorizeRequests().antMatchers("/**").authenticated();
 
	}

上面两个例子中可以看出:().anyRequest().and().authorizeRequests().antMatchers("/test/").authenticated();配置和().antMatchers("/test/").and().authorizeRequests().antMatchers("/**").authenticated();配置后的效果是完全一样的。

authorizeRequests()
授权管理控制的方法,这个方法返回一个对象。Security所有的权限控制都基于这个类进行控制。如:().anyRequest().authenticated();要求所有接口都需要进行权限认证,这个类中的anyRequest()即所有接口,等同于().antMatchers("/").authenticated(); 而其中的authenticated()则要求必须进行权限认证。而().antMatchers("/").permitAll();这个配置中permitAll方法则要求所有接口都不需要进行权限认证。另外这两个代码中antMatchers方法则是配置匹配规则。即哪些接口需要进行权限认证或不需要进行权限认证。

		//所有接口都不需要权限认证
		http.authorizeRequests().antMatchers("/**").permitAll();
		//所有接口都要进行权限认证
		http.authorizeRequests().antMatchers("/**").authenticated();
		//只有以test开头的接口需要进行权限认证
		http.authorizeRequests().antMatchers("/test/**").authenticated();
		http.authorizeRequests().antMatchers("/test/**").hasRole("user").antMatchers("/**").authenticated();

在这个代码中要求以/test开头的路由需要进行角色认证(这里要求user角色),而其他接口只要登录即可访问。当我们需要配置多个角色时可以通过hasAnyRole方法配置多个角色的访问权限,如

http.authorizeRequests().antMatchers("/test/**").hasAnyRole("user","admin").antMatchers("/**").authenticated();