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

问题描述

限时删除!!

我从事内容管理系统的工作,它有五个 antMatcher,如下所示:

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();

假设访问者可以看到根路径下的所有站点(/*),用户只能看到(/user),admin只能看到(/admin),并且有两个登录页面一个是用户另一个是管理员.

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()

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

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).

因此登录页面的规则应该在 /admin/** 规则之前.E.G.

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

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

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

1403页,肝出来的..

09-06 15:45