Spring 启动 oauth2:访问此资源需要完全身份验证

Spring Boot oauth2 : Full authentication is required to access this resource

我正在使用 Postgresql 数据库在 SpringBoot 中开始配置 OAuth2。在邮递员中请求令牌后我收到错误:

{
    "error": "unauthorized",
    "error_description": "Full authentication is required to access this resource"
}

有效载荷:

curl --location --request POST 'localhost:9000/oauth/token' \
     --header 'Content-Type: application/x-www-form-urlencoded' \
     --header 'Authorization: Basic Y2xpZW50SWQ6c2VjcmV0' \
     --data-urlencode 'grant_type=password' \
     --data-urlencode 'username=user' \
     --data-urlencode 'password=pass'

资源服务器配置:

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter
{
    private static final String ROOT_PATTERN = "/**";


    @Override
    public void configure(HttpSecurity http) throws Exception
    {
        http.authorizeRequests()
            .antMatchers(HttpMethod.GET, ROOT_PATTERN).access("#oauth2.hasScope('read')")
            .antMatchers(HttpMethod.POST, ROOT_PATTERN).access("#oauth2.hasScope('write')")
            .antMatchers(HttpMethod.PATCH, ROOT_PATTERN).access("#oauth2.hasScope('write')")
            .antMatchers(HttpMethod.PUT, ROOT_PATTERN).access("#oauth2.hasScope('write')")
            .antMatchers(HttpMethod.DELETE, 
                                          ROOT_PATTERN).access("#oauth2.hasScope('write')");
    }
}

我检查了请求数据,一切都是正确的。我找不到问题是如何发生的。

我发现问题:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
class WebSecurityConfiguration extends WebSecurityConfigurerAdapter
{
    private final DataSource dataSource;
    private PasswordEncoder passwordEncoder;
    private UserDetailsService userDetailsService;

    @Autowired
    public WebSecurityConfiguration(final DataSource dataSource)
    {
        this.dataSource = dataSource;
    }

    @Override
    protected void configure(final AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder()
    {
        if (passwordEncoder == null) {
            this.passwordEncoder = new BCryptPasswordEncoder();
        }

        return passwordEncoder;
    }

    @Bean
    public UserDetailsService userDetailsService()
    {
        if (userDetailsService == null) {
            userDetailsService = new JdbcDaoImpl();
            ((JdbcDaoImpl) userDetailsService).setDataSource(dataSource);
        }

        return userDetailsService;
    }
}

如您所见,我将 JdbcDaoImpl 用于 UserDetailsService,默认情况下它查询 public 模式,但我的模式是别的东西。

现在更改配置如下:

spring.datasource.url=jdbc:postgresql://localhost:5432/MY_DB?currentSchema=MY_SCHEMA_NAME