@安全注释不适用于方法授权

时间:2018-06-29 11:48:50

标签: spring-boot spring-security

我的安全性配置为:

    package com.vaidiksanatansewa.guruji.security;

import javax.sql.DataSource;

import com.vaidiksanatansewa.guruji.service.UserloginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;


    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select username, password, IF(status=1, true, false) as enabled from users where username=? and status=1 ")
                .authoritiesByUsernameQuery("select users.username as username, user_role.role as role from users inner join user_role on users.role_fid=user_role.id where users.username=?  and users.status=1");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and()
                .authorizeRequests().antMatchers( "/appointment/**").permitAll()
                .antMatchers("/user/**").hasAnyAuthority("ADMIN","USER")
                .and()
                .csrf().disable();
    }


}

和在控制器中标注为的方法:

....
    @RequestMapping("/user")
    @Secured("ROLE_ADMIN")
    public List<UserAll> getAll() {

        return userService.getAll();
    }


    @RequestMapping("/user/{id}")
    @Secured("ROLE_USER")
    public UserAll getById(@PathVariable Long id) {

        return userService.getById(id);
    }
......

没有启用方法授权,一切正常,但是启用后,我将获得拒绝访问错误。 似乎所需的一切都是安装程序,但仍然无法正常工作。 您能帮我找出来吗?

1 个答案:

答案 0 :(得分:1)

这感觉很奇怪,但是用@Secured("ROLE_ADMIN")代替@PreAuthorize("hasAuthority('ADMIN')")可以解决问题。我也尝试过进行@Secured("hasRole('ROLE_ADMIN')"),但是那也不起作用。 好吧,到目前为止,它已经解决了。