2016-07-12 46 views
1

任务是创建一个Web应用程序,该应用程序应该可以从具有不同角色的不同用户访问。有些角色可以查看所有页面,有些只能查看所有页面。Java Spring Security无法识别的角色

我对SecurityConfig具有以下配置,但它不起作用。

@Configuration 
@EnableWebSecurity 
@Import(value = { SecurityWebApplicationInitializer.class }) 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    DataSource dataSource; 

    @Autowired 
    private AuthenticationService authenticationService; 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     Md5PasswordEncoder encoder = new Md5PasswordEncoder(); 
     auth.userDetailsService(authenticationService).passwordEncoder(encoder); 
    } 

    @Override 
    public void configure(WebSecurity web) throws Exception { 
     web.ignoring().antMatchers("/assets/**"); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 

    http.authorizeRequests() 
    .antMatchers("/login", "/page1").permitAll() 
    .antMatchers("/**").access("hasRole('RADMIN')") 
    .antMatchers("/login", "/page2").access("hasRole('ADMIN')") 
    .antMatchers("/page2").hasAnyRole("RADMIN", "ADMIN") 
    .and().formLogin() 
    .and().exceptionHandling().accessDeniedPage("/403"); 

    } 

} 

我试图改变hasAnyRole()hasAnyAuthority(),没有效果。几乎每一次我做的改变都不会让ADMIN登录(他只看到/ 403或/ 404),或者让任何人,无论是否授权,都可以看到所有内容。

+0

标准的Spring Security当局'ROLE_'开始,所以这些应该是'ROLE_RADMIN'和'ROLE_ADMIN',除非你自己定义了['AccessDecisionVoter'](http://docs.spring.io/autorepo/docs/spring-security/4.1.0.RELEASE/apidocs/org/springframework/security/access/ AccessDecisionVoter.html)。 – Andreas

+0

试过,没有区别... – mariobgr

+0

你确实检查过ROLE_ADMIN已经分配给用户了,对吗? – Andreas

回答

0

我使用的是Spring-Security 4.0.1.RELEASE,有两个重要的表格,分别是usersauthorities。表authorities应该只有两列(用户名,权限),角色的前缀应为ROLE_ROLE_ADMIN & ROLE_RADMIN像Andreas指出的那样。

尝试保持您的身份验证简单,如下所示,看看它有什么不同,然后添加额外的页面和角色,例如,

@Override 
    protected void configure(HttpSecurity http) throws Exception { 

     http.authorizeRequests(). 
     anyRequest().authenticated().and().formLogin().loginPage("/login.html") 
     .loginProcessingUrl("/login").permitAll().and().logout().logoutSuccessUrl("/") 
     .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll().and().exceptionHandling() 
     .accessDeniedPage("/403.html"); 
    } 
1

那么......问题就像它可以得到的那样愚蠢。

好像与数据库名称被更改提交之一,因此也没有作用(ROLE_NONE)来验证...