我正在尝试创建一个具有多个用户角色和权限的 Spring Boot Web 应用程序。我找到了这个role and privilege for spring security文章最接近我想要的。当我们第一次启动应用程序时,它会创建一个虚拟管理员用户。无需在 AppConfig 文件中为 URL 定义 hasrole
即可正常工作。
现在,当我在 AppConfig 文件中为 URL 定义 hasrole
时,它无法正常工作。请帮我正确配置。这是我的 AppConfig 类的 configure
方法以及 httpSecurity
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").permitAll() //public pages on this directory
.antMatchers("/admin/**").hasRole("ADMIN") //admin pages on this directory
.antMatchers("/user/**").hasAnyRole("ADMIN", "USER") //user pages on this directory
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("email")
.passwordParameter("password").permitAll()
.loginProcessingUrl("/process_login")
.defaultSuccessUrl("/user/dashboard", true)
.failureUrl("/login?error=Invalid username or password!")
.and()
.logout()
.logoutUrl("/perform_logout")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout=You have logged out successfuly!")
.deleteCookies("JSESSIONID")
.clearAuthentication(true)
.invalidateHttpSession(true).permitAll()
.and()
.csrf().disable();
}
当我定义不带星号 (**) 的 .antMatchers("/").permitAll()
时,应用程序会在为管理员定义的 URL 以及用户 URL 上抛出 403 禁止请求错误。如果我在公共(public) URL antmatcher 中放置双星号 (**),例如 .antMatchers("/**").permitAll()
,则应用程序根本不会强制执行角色。并将所有页面公开
我可能有多个 URL 作为公共(public) URL,因此我想定义角色以允许每个人都可以访问公共(public)目录中的所有页面。管理员特定页面将具有管理员前缀,即 /admin/adminPagesURLs
,用户特定页面将具有用户前缀,即 /user/userPagesURLs
提前致谢
最佳答案
映射是分层的,您应该从最具体到不太具体的映射来定义它们。在这种情况下
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
.antMatchers("/**").permitAll()
但是,有人可能会认为这是一种不好的做法,因为您可能无意中暴露了超出应有的信息。例如,如果您将来添加/secret/xyz 并且忘记指定访问控制,那么每个人都可以访问它。甚至 Spring 也鼓励使用“默认拒绝”方法
Always try to use a “deny-by-default” approach where you have a catch-all wildcard (/** or **) defined last and denying access.
我会选择类似的东西
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
.antMatchers("/public/**").permitAll()
.antMatcher("/**").denyAll()
关于java - 如何在java spring boot web应用程序中分配目录级别用户访问权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59703289/