【问题标题】:Not able to access REST controllers in Spring Securtiy even when the role matches即使角色匹配,也无法访问 Spring Security 中的 REST 控制器
【发布时间】:2018-12-30 16:44:21
【问题描述】:

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 电话:-

即使没有提供角色规范,访问此控制器时也会出现 403 错误。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 使用 permitAll(),它无需任何身份验证即可工作。试过 http.authorizeRequests() .antMatchers("/get*").hasAnyRole("USER");但端点仍然没有授权。
    • 我在使用sts ide时遇到过这种情况,但是我在intellij idea中输入了相同的代码,它成功运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2017-03-12
    • 2018-11-28
    • 1970-01-01
    • 2017-10-19
    • 2020-07-19
    相关资源
    最近更新 更多