2016-06-18 101 views
0

我嘗試在誰使用springsecurity角色訪問網址

在誰的配置方法擴展WebSecurityConfigurerAdapter

類彈簧啓動應用程序中添加角色,我有

http.authorizeRequests().antMatchers("/rest/**").authenticated(); 
http.authorizeRequests().antMatchers("/report/**").hasRole("ADMIN"); 
http.csrf().disable(); 
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); 
http.formLogin().successHandler(authenticationSuccessHandler); http.formLogin().failureHandler(authenticationFailureHandler); 
http.logout().logoutUrl("/logout"); 
http.logout().logoutSuccessUrl("/"); 

我實現UserDetailsS​​ervice

public class UserServiceImpl implements UserDetailsService, UserService { 
    @Override 
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { 

    UserApp userapp = repository.findByUsername(userName); 

    if (userapp == null) { 
     throw new UsernameNotFoundException("Username " + userName + " not found"); 
    } 

    return new CustomUserDetails(userapp); 
    } 
} 


public class UserApp { 
    ... 
    ... 
    @Enumerated(EnumType.STRING) 
    private RoleEnum role; 
} 

public enum RoleEnum { 
    ROLE_ADMIN, ROLE_USER; 
} 


public class CustomUserDetails implements UserDetails { 
    private final UserApp userApp; 

    @Override 
    public Collection<? extends GrantedAuthority> getAuthorities() { 
     Collection<GrantedAuthority> authorities = new ArrayList<>(); 
     RoleEnum userRole = this.userApp.getRole(); 

     if (userRole != null) { 
      SimpleGrantedAuthority authority = new SimpleGrantedAuthority(userRole.name()); 
      authorities.add(authority); 
     } 
     return authorities; 
    } 
} 

我的用戶有ROLE_USER,可以訪問t o沒有問題/報告...它不應該。

什麼工作不正常?

回答

0

嘗試用

http.authorizeRequests().antMatchers("/report/**").hasAuthority("ROLE_ADMIN"); 

更新:(上面的回答沒有工作)

試試下面的代碼

http.authorizeRequests() 
    .antMatchers("/report/**").access("hasRole('ROLE_ADMIN')") 
    .anyRequest().fullyAuthenticated() 
+0

同樣的問題,我的用戶機智ROLE_USER卡恩訪問它。 –

+0

只是不能去與我的網頁...我直接...有一個意外的錯誤(type = Unauthorized,status = 401)。 未經授權...只是無法進入登錄頁面... –