2016-07-12 67 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)來驗證...