Spring Oauth2配置授权端点

问题描述 投票:0回答:1

我有使用spring-security-oauth2:2.3.3和spring-boot-starter-security:2.0.2构建的带有REST WS的Spring Web应用程序。但是我无法设置哪些端点受到保护。

ResourceServerConfig

@EnableResourceServer
@Configuration
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/customers", "/v2/**").permitAll()
                .antMatchers("/api/**").authenticated();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationProvider authenticationProvider) {
        return new CustomAuthenticationManager(authenticationProvider);
    }

    @Bean
    public AuthenticationProvider authenticationProvider(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        return new DBAuthenticationProvider(userRepository, passwordEncoder);
    }

}

AuthorizationServerConfig

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("ClientId")
                .secret("secret")
                .authorizedGrantTypes("password")
                .scopes("read", "write");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager);
    }
}

当我首先获得访问令牌时,一切正常,但是我希望端点“ /”,“ / customers”,“ / v2 / **”在没有任何授权的情况下被允许使用。但是当我呼叫“ curl http:// {{host}} /”或“ http:// {{host}} / customers”时,我仍然会收到401:

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

添加“ --header”授权:基本{{base64客户ID:密码}}”也无济于事。怎么可能?

编辑根据spring security permitAll still considering token passed in Authorization header and returns 401 if token is invalid解决,方法是在ResourceServerConfig中添加@Order(1)以覆盖默认的OAuth2。但这仅在添加“ Authorization”标头时才起作用,这不是我的情况。那怎么可能呢?

java spring oauth-2.0 spring-security-oauth2
1个回答
0
投票

将此添加到您的项目中。

@Configuration
public class ResourceServer extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/user/**")
        .authorizeRequests().anyRequest().authenticated();
    }
}

如果要向/user/**发出任何请求,则需要在标头中将访问令牌作为Authorization: Bearer {access_token}传递。所有其他端点将不要求令牌。

© www.soinside.com 2019 - 2024. All rights reserved.