【问题标题】:How to resolve HTTP-403 Forbidden Spring Boot basic authentication using Postman如何使用 Postman 解决 HTTP-403 禁止 Spring Boot 基本身份验证
【发布时间】:2019-10-24 21:15:20
【问题描述】:

我对 Spring Boot 和 Spring Security 还很陌生。通过各种教程和讲座,我实现了一个小型 Spring Boot 应用程序,现在我正在尝试保护我的端点。

我创建了一个扩展 WebSecurityConfigurerAdapter 的安全配置,我用它来保护我的应用程序。

public class LoginSecurityConfig extends WebSecurityConfigurerAdapter
{

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder authManager) throws Exception
    {
        authManager
            .inMemoryAuthentication()
            .withUser("carAdmin").password(passwordEncoder().encode("carAdmin123")).roles("CAR_ADMIN")
            .and()
            .withUser("driverAdmin").password(passwordEncoder().encode("driverAdmin123")).roles("DRIVER_ADMIN", "DRIVER")
            .and()
            .withUser("driver").password("driver@123").roles("DRIVER");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception
    {

        http
            .csrf().disable().formLogin().disable()
            .headers().frameOptions().disable().and()
            .authorizeRequests()
            .antMatchers("/h2-console/**").permitAll()
            .antMatchers("/cars/**").hasAnyRole("CAR_ADMIN")
            .antMatchers("/drivers/**").hasAnyRole("DRIVER_ADMIN", "DRIVER")
            .anyRequest().authenticated();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

在我的 RestAPI 资源中,我使用了@PreAuthorize

@GetMapping("/{carId}")
    @PreAuthorize("hasRole('ROLE_CAR_ADMIN')")
    public CarDTO getCar(@Valid @PathVariable long carId) throws EntityNotFoundException {
        return CarMapper.makeCarDTO(carService.find(carId));
    }

我想用 Postman 测试一下。

另外,我还在网上看到我们可以创建网页来实现身份验证,但我正在寻找非常基本的身份验证。这样,我可以使用基本身份验证和 Postman 对其进行测试。

目前使用这种方法,我在 Postman 中选择 basic auth,传递用户名和密码但得到 Forbidden, access denied.

我不知道我做错了什么或如何解决它。

任何帮助将不胜感激。

【问题讨论】:

    标签: spring spring-boot spring-security


    【解决方案1】:

    尝试将@EnableWebSecurity 添加到您的LoginSecurityConfig,您似乎还没有启用基本身份验证。您可以像这样启用它:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
        http
            .csrf().disable().formLogin().disable()
            ...
    
        http.httpBasic();
    }
    
    

    【讨论】:

    • 嘿,它似乎工作了,但这是第一次。意味着如果我通过不正确的第一个请求,我将无法访问。但是,如果我使用正确的凭据传递第一个请求,如果凭据错误,则传递第二个请求,我仍然可以访问第二个请求.. 这是预期的吗?
    • 查看 BasicAuthenticationFilter 的源代码。您会看到它仅在“用户名与 SecurityContextHolder 不匹配且用户未通过身份验证”时才会重新进行身份验证。我猜第二次,您只更改密码,而不是用户名。由于身份验证保存在会话中,因此您已经第二次进行身份验证,请求将通过。
    猜你喜欢
    • 2015-12-02
    • 2015-09-05
    • 1970-01-01
    • 2016-11-05
    • 2019-04-25
    • 2017-11-02
    • 2014-09-22
    • 2011-02-11
    • 2016-10-16
    相关资源
    最近更新 更多