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

时间:2020-07-31 10:00:42

标签: spring-boot spring-security spring-oauth2

我正在使用Postgresql DB在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'

ResourceServer配置:

@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')");
    }
}

我检查了请求数据,一切正确。我找不到问题怎么发生。

1 个答案:

答案 0 :(得分:1)

我发现了问题:

@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