每当声明停止请求时,HasAnyAuthority总是让我进入api

时间:2017-04-14 21:55:39

标签: authentication spring-security authorization

通过Spring Security我创建了一个方法:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

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

        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/static/build/app.js", "/static/app/styles/*/**", "/static/app/js/*/**",
                        "/static/build/libs.js", "/index.html", "/static/build/*/**", "/", "/static/**").permitAll()
                .antMatchers("/auth/**").permitAll()
                .antMatchers("/api/user/registerClient").permitAll()
                .antMatchers("/api/user/checklogin/**").permitAll()
                .antMatchers("/api/user/getAllAdmins").permitAll()
                .antMatchers("/api/**").hasAnyAuthority(AuthoritiesConstants.CLIENT, AuthoritiesConstants.ADMIN, AuthoritiesConstants.WORKER)
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/")
                .permitAll();

控制器方法的例子:

@RequestMapping(value = "/api/vehicle")
@PreAuthorize("hasAnyAuthority('ADMIN', 'CLIENT')")
@RequestMapping(value = "", method = RequestMethod.GET)
public List<VehicleReservationModel> getVehiclesForClientByLogin(HttpServletRequest request) {
    Principal name = request.getUserPrincipal();
    if (name.getName() == null) {
        throw new RuntimeException("Brak sesji");
    }
    if (roleService.getRoleForUserByLogin(name.getName()).toLowerCase().equals("admin")) {
        return vehicleService.getAllVehicles();
    } else {
        List<VehicleReservationModel> vehicleList = vehicleService.getVehiclesForClientByLogin(name.getName());
        if (vehicleList == null) {
            throw new RuntimeException("Brak pojazdów dla klienta " + name.getName() + " - lista jest pusta");
        }
        return vehicleList;
    }
}

每当我从

中删除ADMIN时都会出现这种情况
@PreAuthorize("hasAnyAuthority('ADMIN', 'CLIENT')")

并发表评论:

.antMatchers("/api/**").hasAnyAuthority(AuthoritiesConstants.CLIENT, AuthoritiesConstants.ADMIN, AuthoritiesConstants.WORKER)

始终让我进入API。我想每当我创造一些特权时,它总能奏效。为什么在上面的例子中我的Spring Security不起作用?

更新 answear用于启用您需要添加的注释PreAuthorize@EnableGlobalMethodSecurity(prePostEnabled = true)

1 个答案:

答案 0 :(得分:3)

您使用@Secured启用了EnableGlobalMethodSecurity#securedEnabled

  

确定是否应启用Spring Security的安全注释。

但您必须使用@PreAuthorize启用EnableGlobalMethodSecurity#prePostEnabled

  

确定是否应启用Spring Security的预发布注释。默认为false。

您修改的Spring Security配置:

process.env.ENV_VARIABLE_NAME