带有hasRole的Spring安全蚂蚁匹配器无法正常工作

时间:2017-01-03 11:47:09

标签: spring security authorization

我已使用WebSecurityConfigAdapter中的方法配置了页面授权:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    super.configure(auth);
    auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    //super.configure(http);
    http.servletApi().rolePrefix("");
    http
      .logout()
          .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/patient/mobile.mvc").hasRole("USER_PATIENT").and().formLogin();
    http.authorizeRequests().antMatchers("/registration/**").hasRole("USER_RECEPTIONIST").and().formLogin();
    http.authorizeRequests().antMatchers("/doctor/**").hasRole("USER_DOCTOR").and().formLogin();
}

在我的userDetailsS​​ervice中我有以下方法,为用户提供他的凭据:

public UserDetails loadUserByUsername(String userEmail) throws UsernameNotFoundException {
    // 1: Check if exist receptionist with given name
    Receptionist receptionist = loginService.getReceptionistByEmail(userEmail);
    if (receptionist != null) {
        return createReceptionistUserDetail(receptionist);
    }
...
}

private UserDetails createReceptionistUserDetail(Receptionist receptionist) {
    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    grantedAuthorities.add(new SimpleGrantedAuthority("USER_RECEPTIONIST"));
    UserDetails ud = new User(receptionist.getEmail(), receptionist.getPasswordHash(), grantedAuthorities);
    return ud;
}

在没有检查角色的情况下,我对正常的身份验证和访问没有任何问题,但是当我添加了基于角色的访问权限时,任何用户都无法访问他的网页。

这可能是错误的实施?

1 个答案:

答案 0 :(得分:1)

好的,似乎问题在于前缀。上面的代码仍未禁用它。

当我在方法中更改方法时:

int

用户可以毫无问题地登录。我试图找到一个简单的解决方案,但这里的解决方案不仅仅是使用“ROLE_”前缀......: - )