栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

requestMatchers()和authorizeRequests()区别

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

requestMatchers()和authorizeRequests()区别

问题描述:

在学习SpringCloud过程中看到以下一段关于OAuth2的代码,非常好奇为什么以"/oauth"开头的请求配置了两次拦截,一个requestMatchers(),一个authorizeRequests()

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
                .requestMatchers()
                .antMatchers("/oauth/**")
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/**").authenticated()
                .and()
                .csrf().disable();
    }

查阅了相关资料,总结如下: 1.requestMatchers()
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.
                requestMatchers().antMatchers("/oauth/**") //  只有以/oauth开头的请求需要进行权限认证
                .and()
                .authorizeRequests().antMatchers("/**").authenticated(); // 其他接口都放行

    }

另一种写法

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.
                requestMatchers().anyRequest() // requestMatchers().anyRequest()表示所有接口不进行认证
                .and()
                .authorizeRequests().antMatchers("/oauth/*").authenticated(); // 只拦截以/oauth开头的请求,并进行认证
    }

综上两种写法,可以看出第一段中的代码是把以上两种写法合并了,目的就是只拦截以/oauth开头的请求,其他请求一律放行。
2.authorizeRequests()有以下几种常见的用法
		// 所有接口都不拦截
		http.authorizeRequests().antMatchers("/**").permitAll();
		// 所有接口都会进行权限拦截
		http.authorizeRequests().antMatchers("/**").authenticated();
		// 只有以oauth开头的接口才进行权限认证,其他请求全部放行
		http.authorizeRequests().antMatchers("/oauth/**").authenticated();
        // 以/test开头的请求需要user角色才行,其他接口只要登陆过就能请求 
        http.authorizeRequests().antMatchers("/test/**").hasRole("user").antMatchers("/**").authenticated();
        // 控制多个角色的时候.hasRole改为.hasAnyRole("user","admin")
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/305280.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号