【问题标题】:Spring security- ant matcher with hasRole is not working具有 hasRole 的 Spring security-ant matcher 不起作用
【发布时间】:2017-01-03 11:47:09
【问题描述】:

我已经使用 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;
}

我在不勾选角色的情况下正常认证和访问没有问题,但是当我添加了基于角色的访问时,任何用户都无法访问他的网页。

这里可能有什么错误?

【问题讨论】:

    标签: spring security authorization


    【解决方案1】:

    好的,看来问题出在前缀上。上面的代码仍然没有禁用它。

    当我改变方法中的方法时:

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

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

    【讨论】:

      猜你喜欢
      • 2015-08-27
      • 2017-06-16
      • 2015-12-09
      • 1970-01-01
      • 2020-07-25
      • 2019-12-18
      • 2018-11-08
      相关资源
      最近更新 更多