Spring 5授权未按预期工作



我是Spring Security的新手。在我的一个示例示例中,我们使用Spring Security 5.4.5和Spring Boot。

我有下面的配置类,其中我试图在/user中应用Spring安全认证/授权和/adminREST API的端点。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
PasswordEncoder bcryptPasswordEncoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.anonymous().principal("guest").authorities("GUEST_ROLE")//Provide the name and role to the annonymous user
.and()
.authorizeRequests()
.antMatchers("/register").anonymous()//allows registration page to be accessed by annonymous users only
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET,"/admin").hasAnyRole("ADMIN_ROLE")
.antMatchers(HttpMethod.GET,"/user").hasAnyRole("STUDENT_ROLE", "ADMIN_ROLE")
.and()
.httpBasic();

}
@Override
@Bean
protected UserDetailsService userDetailsService() {
UserDetails annaSmithUserDetails = User.builder()
.username("annasmith")
.password(bcryptPasswordEncoder.encode("password"))//default password enoder is bcrypt
.roles("STUDENT_ROLE", "ADMIN_ROLE") //role of the user
.authorities("STUDENT_READ","STUDENT_WRITE","COURSE_READ","COURSE_WRITE") //authorities or we can say permission assigned to the user
.build();
return new InMemoryUserDetailsManager(annaSmithUserDetails);//can configure different
}
}

根据上面的Spring配置,/user角色和ADMIN角色都可以访问,/ADMIN角色可以访问。

当我试图在浏览器中访问/user时,它显示用户名和密码弹出,一旦我输入配置的用户的正确凭据,它就不工作并给出403错误。

我有以下三个问题

  1. 我在控制台日志中没有看到任何错误,是否有一种方法可以看到为什么Spring Security显示403错误?
  2. 当我无法访问REST API端点时,上述Spring安全配置的问题是什么?
  1. 我在控制台日志中没有看到任何错误,是否有一种方法可以看到为什么spring安全显示403错误?

通过启用spring调试日志,如何做到这一点可以通过简单的谷歌搜索或在spring文档中找到。学会调试你的应用程序(调试你的应用程序应该是你学习的第一件事,应该在请求堆栈溢出之前完成)) .

当我无法访问REST API端点时,上述spring安全配置的问题是什么?

可能是几个问题,因为您没有透露如何访问应用程序。通过curl, web浏览器,在react应用程序中使用fetch的另一个web客户端等等。当您询问堆栈溢出时,也应该包括在其中,以便人们能够重现手头的问题。

但列出一些可能出错的事情:

  • 您的请求不正确
  • 你的密码可能不正确,因为我看到你加密你的密码不正确(请参阅如何实际做到这一点的文档)
  • 确保您的密码以正确的前缀存储,或者在构建用户时使用UserBuilder users = User.withDefaultPasswordEncoder();
  • 如果要遵循任何标准,
  • 角色的定义应该没有前缀或后缀(_ROLE)。
  • 在您登录后,您是否被重定向到您不允许访问的内容?

正如你所看到的,有几件事可能是错误的,但你提供的信息太少,无法回答,在询问堆栈溢出之前,你可以做很多事情。

答案是模糊的,因为问题是模糊的。

最新更新