2017-05-19 21 views
0

我已经使用mongo数据库的generator-jhipster创建了一个项目。@Secured(“<new_role>”)显示access_denied

我想添加在JHI_AUTHORITY一个新的角色,所以我已经在蒙戈{"_id" : "ROLE_MANAGER"}

插入一个新的纪录JHI_AUTHORITY文件现在我想,只有用两种ROLE_ADMINROLE_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(); 
    } 
} 
+0

请显示您的安全配置类 –

+0

@GaëlMarziou我在我的问题中添加了安全配置类。请参阅更新。 –

回答

0

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

而在你的数据库,你需要将角色保存为ROLE_NAME,当你在@Secured使用它们,@PreAuthorize等使用它们没有前缀(例如NAME)。

+0

我已经尝试过您的答案,并且使用'@ Secured'和'MANAGER'作用而没有'ROLE_'前缀,但它不起作用。响应是'access_denied'。 –

+0

你把注释放在控制器上吗?如果你这样做,它将永远不会工作,因为春季服务代理而不是类本身。你需要把它放在你的服务层/在配置文件中使用一个ant匹配器/创建一个控制器扩展的接口,并将其放在那里 – Tom

+0

我已经尝试在我的配置类中使用antMatchers,并使用以下LOC'http.antMatchers(HttpMethod .GET,“/api/XXX").hasAnyAuthority("ROLE_ADMIN”,“MANAGER”);'但是这也只允许访问管理员而不是管理员。 –