本文介绍了Spring Security中的多个antMatchers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在内容管理系统上工作,该系统具有五个 antMatchers ,如下所示:

http.authorizeRequests()
        .antMatchers("/", "/*.html").permitAll()
        .antMatchers("/user/**").hasRole("USER")
        .antMatchers("/admin/**").hasRole("ADMIN")
        .antMatchers("/admin/login").permitAll()
        .antMatchers("/user/login").permitAll()
        .anyRequest().authenticated()
        .and()
        .csrf().disable();

,这意味着访问者可以在根路径(/*)上看到所有站点,并且用户只能看到(/user),管理员只能看到(/admin),并且有两个登录页面供用户使用另一个用于管理员.

该代码似乎可以正常工作,但管理部分除外-它不起作用,但返回拒绝访问异常.

解决方案

我认为问题出在您规则的顺序中:

.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/admin/login").permitAll()

规则的顺序很重要,更具体的规则应排在第一位.现在,以/admin开头的所有内容都将需要具有ADMIN角色的经过身份验证的用户,甚至是/admin/login路径(因为/admin/login已经与/admin/**规则匹配,因此忽略了第二个规则).

因此,登录页面的规则应先于/admin/**规则.例如

.antMatchers("/admin/login").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")

I work on content management system, that has five antMatchers like the following:

http.authorizeRequests()
        .antMatchers("/", "/*.html").permitAll()
        .antMatchers("/user/**").hasRole("USER")
        .antMatchers("/admin/**").hasRole("ADMIN")
        .antMatchers("/admin/login").permitAll()
        .antMatchers("/user/login").permitAll()
        .anyRequest().authenticated()
        .and()
        .csrf().disable();

which suppose to mean that the visitors can see all site at root path (/*), and users can see only (/user), admin can see only (/admin), and there are two login pages one for users and another for admin.

The code seems to work fine, except the admin section - it doesn't work but return access denied exception.

解决方案

I believe that the problem is in the order of your rules:

.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/admin/login").permitAll()

The order of the rules matters and the more specific rules should go first. Now everything that starts with /admin will require authenticated user with ADMIN role, even the /admin/login path (because /admin/login is already matched by the /admin/** rule and therefore the second rule is ignored).

The rule for the login page should therefore go before the /admin/** rule. E.G.

.antMatchers("/admin/login").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")

这篇关于Spring Security中的多个antMatchers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 13:22