【发布时间】:2021-05-30 03:37:00
【问题描述】:
我是 Spring Security 的新手。在我的一个示例示例中,我们使用 Spring Security 5.4.5 和 Spring Boot。
我在下面的配置类中尝试在 REST API 的 /user 和 /admin 端点中应用 Spring Security 身份验证/授权。
@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 角色都可以访问 /user,ADMIN 角色可以访问 /admin。
当我尝试在浏览器中访问 /user 时,它会显示用户名和密码弹出窗口,一旦我输入配置用户的正确凭据,它就无法正常工作并给出 403 错误。
我有以下三个问题
- 我没有在控制台日志中看到任何错误,有什么方法可以让我看到 Spring Security 显示 403 错误的原因吗?
- 由于我无法访问 REST API 端点,上述 Spring Security 配置有什么问题?
【问题讨论】:
标签: java spring spring-boot spring-security