Spring Oauth2配置授权端点

时间:2018-06-04 13:43:34

标签: java spring oauth-2.0 spring-security-oauth2

我使用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:密码}}“也没有帮助。这怎么可能?

修改 根据{{​​3}}解决方法,将@Order(1)添加到ResourceServerConfig以覆盖默认的OAuth2。但是,只有在添加“授权”标题时才会启动,这不是我的情况。那怎么可能呢?

1 个答案:

答案 0 :(得分: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}传递。所有其他端点都不会要求令牌。