我想在我的项目中配置HTTP安全性,以便具有MODERATOR角色的用户可以访问端点/api/course
。目前,我的configure方法如下所示:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/course/**").permitAll()
.anyRequest().authenticated();
httpSecurity.addFilterBefore(authTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
当然,我尝试了以下解决方案:
.antMatchers("/api/course/**").hasRole("MODERATOR")
和
.antMatchers("/api/course/**").access("hasRole('MODERATOR')")
但是,每次我收到401响应状态。我正在询问有关如何配置Spring Security以获得预期效果的提示?
.antMatchers("/api/course/**").hasRole("MODERATOR")
希望用户具有ROLE_MODERATOR
角色,它将自动向其添加ROLE_
前缀。因此,如果主持人的角色名称仅为MODERATOR
,则他们将不匹配,因此他无法访问和接收401响应。
您可以更改使用
.antMatchers("/api/course/**").hasAuthority("MODERATOR")
不会添加ROLE_
前缀并且与用户的角色名称完全匹配。