【问题标题】:How to restrict access to html pages based on roles with spring security?如何使用spring security根据角色限制对html页面的访问?
【发布时间】:2023-04-08 21:54:01
【问题描述】:

我希望用户能够根据他们的角色访问 html 页面。例如,只有 HR 角色才能查看 settings.html 页面,只有管理者才能看到 pendingrequest.html。

这是我的安全配置:

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private DatabaseAuthenticationProvider authenticationProvider;


        @Override
        public void configure(WebSecurity web) throws Exception {

            web.ignoring().antMatchers("/js/**", "/css/**", "/img/**");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.formLogin().loginPage("/login").failureUrl("/login").defaultSuccessUrl("/")
                    .and().logout().logoutSuccessUrl("/login")
                    .and().authorizeRequests().antMatchers("/login").permitAll()
                    .antMatchers("/settings.html").hasRole("HR")
                    .antMatchers("/pendingRequests.html").hasRole("MANAGER")
                    .antMatchers("/settings.html","/pendingRequests.html").hasRole("ADMIN")
                    .anyRequest().authenticated().and().csrf().disable();
        }



 @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(authenticationProvider).eraseCredentials(false);
    }
}

由于某种原因,我在那里尝试的方法不起作用,无论我担任什么角色,我都看不到这些页面。

【问题讨论】:

    标签: java html spring spring-security roles


    【解决方案1】:

    Spring security 默认为安全检查中定义的所有角色添加ROLE_ 前缀。

    您可以将角色名称重命名为具有 ROLE_ 前缀或从配置中删除该前缀 (How do I remove the ROLE_ prefix from Spring Security with JavaConfig?)

    【讨论】:

      猜你喜欢
      • 2012-09-14
      • 1970-01-01
      • 2018-11-28
      • 2012-12-27
      • 1970-01-01
      • 2018-06-06
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多