即使角色匹配,也无法在Spring Securtiy中访问REST控制器

时间:2018-12-30 16:44:22

标签: spring spring-boot spring-security spring-security-rest

WebSecurityConfig类如下:-

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {



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

        http.authorizeRequests()
                .antMatchers("/get*").hasAnyRole();


    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user1").password("user1Pass")
                .authorities("USER");
                //.and().withUser("admin").password("adminPass")
                //.authorities("ADMIN");
    }


    /*@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance())
                .withUser("test").password("test123").roles("USER").and().
                withUser("test1").password("test123").roles("ADMIN");
    }

}*/
    }

下面是REST控制器:-

@RequestMapping(value="/getprofessors", method=RequestMethod.GET)
    public List<Professor> getProfessors() {

        //return service.findProfessors();

        List<Professor> Professors = professorRepo.findAll();

        return  Professors;

    }

下图代表我正在进行的POSTMAN呼叫:-

Postman call I'm trying to make

即使没有提供角色说明,访问此控制器时也会收到403错误。

1 个答案:

答案 0 :(得分:0)

您是否检查过antMatchers()的其他方法?我的意思是allowAll()和其他。 hasAnyRole()可能有问题,因为它需要String []。它是空的,因此可能会出现问题。