【问题标题】:@Secured("<new_role>") shows access_denied@Secured("<new_role>") 显示 access_denied
【发布时间】:2017-10-19 10:32:38
【问题描述】:

我已经使用带有 mongo 数据库的 generator-jhipster 创建了一个项目。

我想在 JHI_AUTHORITY 中添加一个新角色,所以我在 mongo {"_id" : "ROLE_MANAGER"} 的 JHI_AUTHORITY 文档中插入了一条新记录

现在我希望只有ROLE_ADMIN 或ROLE_MANAGER 的用户才有权使用其中一个api。 所以我在我的 api 中添加了以下 LOC:

@secured({"ROLE_ADMIN", "ROLE_MANAGER"})

但是当我尝试使用具有角色的用户访问 api 时:ROLE_ADMIN 效果很好,但是当用户具有角色:ROLE_MANAGER 时,它显示错误:

{ "error": "access_denied", "error_description": "Access is denied" }

如果缺少任何步骤,请告诉我?

安全配置类如下:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Inject
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Inject
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
            .antMatchers("/scripts/**/*.{js,html}")
            .antMatchers("/bower_components/**")
            .antMatchers("/i18n/**")
            .antMatchers("/assets/**")
            .antMatchers("/swagger-ui.html")
            .antMatchers("/api/register")
            .antMatchers("/api/activate")
            .antMatchers("/api/account/reset_password/init")
            .antMatchers("/api/account/reset_password/finish")
            .antMatchers("/test/**");
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
        return new SecurityEvaluationContextExtension();
    }
}

【问题讨论】:

  • 请显示您的安全配置类
  • @GaëlMarziou 我在我的问题中添加了安全配置类。请查看更新。

标签: mongodb spring-boot jhipster


【解决方案1】:

Spring 安全角色具有默认前缀 - ROLE_

在您的数据库中,当您在@Secured、@PreAuthorize 等中使用角色时,您需要将角色另存为ROLE_NAME,使用不带前缀的角色(例如NAME)。

【讨论】:

  • 我已经尝试了您的答案,并使用@Secured 和MANAGER 角色,没有ROLE_ 前缀,但它不起作用。回复是access_denied。
  • 您是否将注释放在控制器本身上?如果你这样做,它将永远不会作为spring服务代理而不是类本身。您需要将其放在您的服务层/在配置文件中使用 ant 匹配器/创建控制器扩展的接口并将其放在那里
  • 我已经尝试在我的配置类中使用 antMatchers 并遵循 LOC http.antMatchers(HttpMethod.GET, "/api/XXX").hasAnyAuthority("ROLE_ADMIN", "MANAGER"); 但这也仅授予管理员访问权限,而不授予经理访问权限。
猜你喜欢
  • 2023-04-08
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-09
  • 2017-10-31
  • 2017-10-13
  • 2019-03-11
  • 1970-01-01
相关资源
最近更新 更多