Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Spring Boot OAuth2保护Rest API_Spring_Spring Boot_Spring Security_Oauth 2.0 - Fatal编程技术网

如何使用Spring Boot OAuth2保护Rest API

如何使用Spring Boot OAuth2保护Rest API,spring,spring-boot,spring-security,oauth-2.0,Spring,Spring Boot,Spring Security,Oauth 2.0,我想创建一个带有OAuth2集成的示例Spring Boot应用程序,该应用程序具有一个CustomTokenEnhancer,它应该向没有访问令牌的客户机公开/oauth/token URL,但只有在具有有效访问令牌的情况下才能查询所有其他URL。 我可以设置CustomTokenEnhancer,当/oauth/token请求时,我可以通过它发送额外的内容。 Application.java-Spring启动应用程序类 AuthorizationServerConfiguration.ja

我想创建一个带有OAuth2集成的示例Spring Boot应用程序,该应用程序具有一个CustomTokenEnhancer,它应该向没有访问令牌的客户机公开/oauth/token URL,但只有在具有有效访问令牌的情况下才能查询所有其他URL。

我可以设置CustomTokenEnhancer,当/oauth/token请求时,我可以通过它发送额外的内容。


Application.java-Spring启动应用程序类
AuthorizationServerConfiguration.java-授权服务器
ResourceServer.java-资源服务器
OAuth2SecurityConfiguration.java-扩展WebSecurity配置适配器并定义内存用户
CustomTokenEnhancer.java-使用访问令牌发送其他内容,如cookie

在OAuth2SecurityConfiguration.java中,我正在配置3个URL,/oauth/token可以由任何拥有clientId和secret的人查询,一旦您拥有了访问令牌。客户端应该能够查询我案例中的所有其他URL
/test
/inventory/sku/{skuID}

protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/oauth/token").permitAll().antMatchers("/inventory/**","/test").hasAnyRole("USER","ADMIN");

}
但当我查询/测试或/库存/sku/1100时,我得到了禁止的401。

我需要帮助,使两个URL/test和/inventory/sku/1100仅可用于访问令牌和/oauth/token而不可用于访问令牌。

OAuth2SecurityConfiguration.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    public OAuth2SecurityConfiguration() {
        System.out.println("OAuth2SecurityConfiguration()");
    }

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {

        System.out.println("OAuth2SecurityConfiguration globalUserDetails() ,invoke BJSCustomAuthentication");

        auth.inMemoryAuthentication() // authenticationProvider(new
                                        // BJsCustomAuthentication());
                .withUser("bill").password("abc123").roles("ADMIN").and().withUser("bob").password("abc123")
                .roles("USER");
    }

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

        http.authorizeRequests().antMatchers("/oauth/token").permitAll().antMatchers("/inventory/**","/test").hasAnyRole("USER","ADMIN");
        //http.authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll().anyRequest().authenticated().and()
            //  .httpBasic().and().csrf().disable();

    }

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

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore) {
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        return handler;
    }

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }

}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    public AuthorizationServerConfiguration() {

        System.out.println("AuthorizationServerConfiguration()");
    }

    @Autowired
    AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        System.out.println("AuthorizationServerConfiguration configure()");

        //endpoints.authenticationManager(authenticationManager).tokenEnhancer(tokenEnhancer()).tokenStore(tokenStore());

        endpoints.authenticationManager(authenticationManager);
    }

    /*@Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }*/

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        System.out.println("OAUTH CLIENT CONFIGURED in AuthorizationServerConfiguration !!!");

        clients.inMemory().withClient("my-trusted-client")
        .authorizedGrantTypes("password", "authorization_code",
                "refresh_token", "implicit")
        .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
        .scopes("read", "write", "trust").resourceIds("sparklr")
        .accessTokenValiditySeconds(60).
        and()
        .withClient("my-client-with-registered-redirect")
        .authorizedGrantTypes("authorization_code").authorities("ROLE_CLIENT")
        .scopes("read", "trust").resourceIds("sparklr")
        .redirectUris("http://anywhere?key=value").
        and()
        .withClient("angular") //my-client-with-secret
        .authorizedGrantTypes("password","refresh")
        .authorities("ROLE_CLIENT").scopes("read","write").resourceIds("sparklr").accessTokenValiditySeconds(100)
        .secret("secret");
    }


}
import java.util.HashMap;
import java.util.Map;

import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

public class CustomTokenEnhancer implements TokenEnhancer {

    public CustomTokenEnhancer() {
        System.out.println("CustomTokenEnhancer()");
    }

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

        System.out.println("Custom Token Enhancer Initialized");

        WCSResponse wcsResponse = (WCSResponse) authentication.getPrincipal();
        authentication.getOAuth2Request().getRequestParameters();

        final Map<String, Object> additionalInfo = new HashMap<>();

        additionalInfo.put("wcsResponse", wcsResponse);

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

        return accessToken;
    }

}
AuthorizationServer.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    public OAuth2SecurityConfiguration() {
        System.out.println("OAuth2SecurityConfiguration()");
    }

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {

        System.out.println("OAuth2SecurityConfiguration globalUserDetails() ,invoke BJSCustomAuthentication");

        auth.inMemoryAuthentication() // authenticationProvider(new
                                        // BJsCustomAuthentication());
                .withUser("bill").password("abc123").roles("ADMIN").and().withUser("bob").password("abc123")
                .roles("USER");
    }

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

        http.authorizeRequests().antMatchers("/oauth/token").permitAll().antMatchers("/inventory/**","/test").hasAnyRole("USER","ADMIN");
        //http.authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll().anyRequest().authenticated().and()
            //  .httpBasic().and().csrf().disable();

    }

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

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore) {
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        return handler;
    }

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }

}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    public AuthorizationServerConfiguration() {

        System.out.println("AuthorizationServerConfiguration()");
    }

    @Autowired
    AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        System.out.println("AuthorizationServerConfiguration configure()");

        //endpoints.authenticationManager(authenticationManager).tokenEnhancer(tokenEnhancer()).tokenStore(tokenStore());

        endpoints.authenticationManager(authenticationManager);
    }

    /*@Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }*/

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        System.out.println("OAUTH CLIENT CONFIGURED in AuthorizationServerConfiguration !!!");

        clients.inMemory().withClient("my-trusted-client")
        .authorizedGrantTypes("password", "authorization_code",
                "refresh_token", "implicit")
        .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
        .scopes("read", "write", "trust").resourceIds("sparklr")
        .accessTokenValiditySeconds(60).
        and()
        .withClient("my-client-with-registered-redirect")
        .authorizedGrantTypes("authorization_code").authorities("ROLE_CLIENT")
        .scopes("read", "trust").resourceIds("sparklr")
        .redirectUris("http://anywhere?key=value").
        and()
        .withClient("angular") //my-client-with-secret
        .authorizedGrantTypes("password","refresh")
        .authorities("ROLE_CLIENT").scopes("read","write").resourceIds("sparklr").accessTokenValiditySeconds(100)
        .secret("secret");
    }


}
import java.util.HashMap;
import java.util.Map;

import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

public class CustomTokenEnhancer implements TokenEnhancer {

    public CustomTokenEnhancer() {
        System.out.println("CustomTokenEnhancer()");
    }

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

        System.out.println("Custom Token Enhancer Initialized");

        WCSResponse wcsResponse = (WCSResponse) authentication.getPrincipal();
        authentication.getOAuth2Request().getRequestParameters();

        final Map<String, Object> additionalInfo = new HashMap<>();

        additionalInfo.put("wcsResponse", wcsResponse);

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

        return accessToken;
    }

}
CustomTokenEnhancer.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    public OAuth2SecurityConfiguration() {
        System.out.println("OAuth2SecurityConfiguration()");
    }

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {

        System.out.println("OAuth2SecurityConfiguration globalUserDetails() ,invoke BJSCustomAuthentication");

        auth.inMemoryAuthentication() // authenticationProvider(new
                                        // BJsCustomAuthentication());
                .withUser("bill").password("abc123").roles("ADMIN").and().withUser("bob").password("abc123")
                .roles("USER");
    }

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

        http.authorizeRequests().antMatchers("/oauth/token").permitAll().antMatchers("/inventory/**","/test").hasAnyRole("USER","ADMIN");
        //http.authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll().anyRequest().authenticated().and()
            //  .httpBasic().and().csrf().disable();

    }

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

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore) {
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        return handler;
    }

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }

}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    public AuthorizationServerConfiguration() {

        System.out.println("AuthorizationServerConfiguration()");
    }

    @Autowired
    AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        System.out.println("AuthorizationServerConfiguration configure()");

        //endpoints.authenticationManager(authenticationManager).tokenEnhancer(tokenEnhancer()).tokenStore(tokenStore());

        endpoints.authenticationManager(authenticationManager);
    }

    /*@Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }*/

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        System.out.println("OAUTH CLIENT CONFIGURED in AuthorizationServerConfiguration !!!");

        clients.inMemory().withClient("my-trusted-client")
        .authorizedGrantTypes("password", "authorization_code",
                "refresh_token", "implicit")
        .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
        .scopes("read", "write", "trust").resourceIds("sparklr")
        .accessTokenValiditySeconds(60).
        and()
        .withClient("my-client-with-registered-redirect")
        .authorizedGrantTypes("authorization_code").authorities("ROLE_CLIENT")
        .scopes("read", "trust").resourceIds("sparklr")
        .redirectUris("http://anywhere?key=value").
        and()
        .withClient("angular") //my-client-with-secret
        .authorizedGrantTypes("password","refresh")
        .authorities("ROLE_CLIENT").scopes("read","write").resourceIds("sparklr").accessTokenValiditySeconds(100)
        .secret("secret");
    }


}
import java.util.HashMap;
import java.util.Map;

import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

public class CustomTokenEnhancer implements TokenEnhancer {

    public CustomTokenEnhancer() {
        System.out.println("CustomTokenEnhancer()");
    }

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

        System.out.println("Custom Token Enhancer Initialized");

        WCSResponse wcsResponse = (WCSResponse) authentication.getPrincipal();
        authentication.getOAuth2Request().getRequestParameters();

        final Map<String, Object> additionalInfo = new HashMap<>();

        additionalInfo.put("wcsResponse", wcsResponse);

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

        return accessToken;
    }

}
import java.util.HashMap;
导入java.util.Map;
导入org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
导入org.springframework.security.oauth2.common.OAuth2AccessToken;
导入org.springframework.security.oauth2.provider.OAuth2Authentication;
导入org.springframework.security.oauth2.provider.token.TokenEnhancer;
公共类CustomTokenEnhancer实现了TokenEnhancer{
公共CustomTokenEnhancer(){
System.out.println(“CustomTokenEnhancer()”;
}
@凌驾
公共OAuth2AccessToken增强(OAuth2AccessToken accessToken,OAuth2Authentication身份验证){
System.out.println(“自定义令牌增强器已初始化”);
WCSResponse WCSResponse=(WCSResponse)身份验证。getPrincipal();
authentication.getOAuth2Request().getRequestParameters();
final Map additionalInfo=新HashMap();
附加信息put(“wcsResponse”,wcsResponse);
((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(additionalInfo);
返回accessToken;
}
}

您如何请求休息?你能发送客户端代码吗?或者访问被拒绝例外嗨,我有两个简单的rest控制器localhost:9080/InventoryService/inventory/sku/1100和localhost:9080/test。我想保护这些,任何想要访问这些的客户端都应该有访问令牌,访问令牌可以实现localhost:9080/oauth/token,当我发送令牌时,我使用自定义令牌增强器发送cookie。希望你理解我想做的事情,我的测试控制器和库存控制器与此类似,为什么你想通过cookie发送令牌,我认为这在oauth中不是正常的方式,你可以将令牌添加到头请求中,请求是ajax?我将oauth令牌作为Json响应和一些附加的东西发送。我只需要配置来保护其余URL。在OAuth2SecurityConfiguration.java配置方法中,您可以看到我在尝试什么