【问题标题】:Spring 5 Authorization not working as expectedSpring 5 授权未按预期工作
【发布时间】: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 错误。

我有以下三个问题

  1. 我没有在控制台日志中看到任何错误,有什么方法可以让我看到 Spring Security 显示 403 错误的原因吗?
  2. 由于我无法访问 REST API 端点,上述 Spring Security 配置有什么问题?

【问题讨论】:

    标签: java spring spring-boot spring-security


    【解决方案1】:
    1. 我没有在控制台日志中看到任何错误,有什么方法可以让我看到 spring security 显示 403 错误的原因吗?

    通过启用 spring 调试日志,how to do this can be done with a simple google search 或在 spring 文档中找到。学习调试您的应用程序(调试您的应用程序应该始终是您学习的第一件事,并且应该在询问堆栈溢出之前完成)。

    由于我无法访问 REST API 端点,上述 spring 安全配置有什么问题?

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

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

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

    因为问题含糊,所以答案含糊。

    【讨论】:

    • @感谢您分享详细信息。我能够解决问题,并确保下次在问题中提供足够的详细信息。
    • 我已经在问题中提到了以下语句当我尝试在浏览器中访问 /user 时,它会显示用户名和密码弹出窗口,一旦我输入配置用户的正确凭据,它就不起作用并给出 403 错误。所以当你说我没有提到我如何尝试访问应用程序时,我不明白你的评论,你能详细说明一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 2015-04-01
    • 2014-07-02
    • 2020-01-18
    相关资源
    最近更新 更多