【问题标题】:how to assign directory level user access in java spring boot web applicationjava - 如何在Java Spring Boot Web应用程序中分配目录级用户访问权限
【发布时间】:2020-04-29 09:06:22
【问题描述】:

我正在尝试制作一个具有多个用户角色和权限的 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 禁止请求错误。如果我像 .antMatchers("/**").permitAll() 这样在公共 URL 匹配器中添加双星号 (**),则应用程序根本不会强制执行角色。并公开所有页面
我可能有多个 URL 作为公共 URL,因此,我想定义角色以允许每个人都可以访问公共目录中的所有页面。特定于管理员的页面将具有管理员前缀,即/admin/adminPagesURLs,特定于用户的页面将具有用户前缀,即/user/userPagesURLs

提前感谢

【问题讨论】:

    标签: java spring spring-boot spring-security


    【解决方案1】:

    映射是分层的,您应该从最具体到不太具体的映射来定义它们。在这种情况下

    .antMatchers("/admin/**").hasRole("ADMIN") 
    .antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
    .antMatchers("/**").permitAll()
    

    但是,有人可能会争辩说这是一种不好的做法,因为您可能无意中暴露了超出应有的信息。例如,如果您将来添加 /secret/xyz 并忘记指定访问控制,则每个人都可以访问它。甚至 spring 也鼓励使用“默认拒绝”的方法

    始终尝试使用“默认拒绝”的方法 通用通配符(/** 或 **)最后定义并拒绝访问。

    我会选择类似的东西

    .antMatchers("/admin/**").hasRole("ADMIN") 
    .antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
    .antMatchers("/public/**").permitAll()
    .antMatcher("/**").denyAll()
    

    【讨论】:

    • 我在您的回答中尝试了第二种方法。但应用程序仍然在管理员和用户网址上抛出 403
    • 您登录了吗?你是如何命名你的角色的?
    • 是的,我已登录。在数据库中,我拥有 ROLE_AMDIN 和 ROLE_USER 等角色
    猜你喜欢
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 2011-02-16
    • 2021-05-24
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多