Spring OAuth2资源仅允许客户端和令牌自动创建

时间:2015-01-26 02:28:17

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

我有一个使用OAuth2 password grant type来管理其资源的用户授权的应用。所有应用程序资源仅允许具有一次提供的令牌的客户端代表某些用户进行访问,除了用于创建用户的URI,我想要的只有已验证的客户端才能访问它。我使用spring-security-oauth2作为我的OAuth实现,但无法弄清楚如何以比下面描述的方式更简单的方式实现这一点:

POST /users只能由经过身份验证的客户端访问。

目前,我通过删除@EnableAuthorizationServer并创建新类并扩展AuthorizationServerSecurityConfiguration类和重写方法configure( HttpSecurity http )以及创建新的@Configuration类来找到解决方法。 @Import AuthorizationServerEndpointsConfigurationCustomAuthorizationServerSecurityConfiguration。 问题是,在我的新自定义class中,我需要在覆盖的方法中覆盖并复制/粘贴整个方法原始代码,结束如下:

@Override protected void configure( HttpSecurity http ) throws Exception { AuthorizationServerSecurityConfigurer configurer = new AuthorizationServerSecurityConfigurer(); FrameworkEndpointHandlerMapping handlerMapping = endpoints.oauth2EndpointHandlerMapping(); http.setSharedObject(FrameworkEndpointHandlerMapping.class, handlerMapping); configure(configurer); http.apply(configurer); String tokenEndpointPath = handlerMapping.getServletPath("/oauth/token"); String tokenKeyPath = handlerMapping.getServletPath("/oauth/token_key"); String checkTokenPath = handlerMapping.getServletPath("/oauth/check_token"); http .authorizeRequests() .antMatchers(tokenEndpointPath).fullyAuthenticated() .antMatchers( HttpMethod.POST, "/users/**").fullyAuthenticated() .antMatchers(tokenKeyPath).access(configurer.getTokenKeyAccess()) .antMatchers(checkTokenPath).access(configurer.getCheckTokenAccess()) .and() .requestMatchers() .requestMatchers( new AntPathRequestMatcher(tokenKeyPath), new AntPathRequestMatcher(tokenEndpointPath), new AntPathRequestMatcher(checkTokenPath), new AntPathRequestMatcher("/users/**", HttpMethod.POST.name())); http.setSharedObject(ClientDetailsService.class, clientDetailsService); } 我的第一个问题是,这是一个更好的方法吗?

我想要做的第二件事是在创建新用户时(在URI POST /users中)自动创建按密码授予类型的AccessToken,我无法想办法做任何事情。

有人可以提供有关这两种需求的任何见解吗?

由于

1 个答案:

答案 0 :(得分:0)

不确定这是不是你问的问题,但我想知道你想要的是什么    使用POST方法为/ users端点上的请求配置特定的安全约束。所以    我就是这样做的。我不认为这是延伸    推荐的方式AuthorizationServerSecurityConfiguration是必要的    通常只在您的主要内容中延伸WebSecurityConfigurerAdapter   安全配置类,请记住,您可以为多个端点多次配置HttpSecurity,但如果在多个位置配置相同的端点,则最后一次配置读取将是活动的

           @EnableWebSecurity public class SecurityConfiguration extends
           WebSecurityConfigurerAdapter {
           //other methods ...

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

           @Order(1)
           @Override 
           protected void configure(HttpSecurity http) throws Exception {  
                //configure your path here
                //I purposly configured GET user to
                // permit all to see diference
                //for example
                // @formatter:off
                http
                .authorizeRequests()
                .antMatchers(HttpMethod.GET,"/user")
                .permitAll() 
                .antMatchers(HttpMethod.POST,"/user")
                .fullyAuthenticated()
                .and().csrf().disable()
                .formLogin();
                // @formatter:on
            }

       }

然后在你的Ouath配置中

@Configuration
public class OAuth2ServerConfiguration {

    private static final String RESOURCE_ID = "restservice";

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            // @formatter:off
            resources
                .resourceId(RESOURCE_ID);
            // @formatter:on
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            // @formatter:off
             http
                .requestMatchers()
                .antMatchers("/resources/**","/greeting")
                .and() 
                .authorizeRequests()
                .antMatchers("/resources").access("#oauth2.hasScope('read') or hasRole('ROLE_USER')")
                .antMatchers("/greeting").access("#oauth2.hasScope('read')"); 
            }
    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        private TokenStore tokenStore = new InMemoryTokenStore();

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            // @formatter:off
            endpoints
                .tokenStore(this.tokenStore)
                .authenticationManager(authenticationManager);
                // @formatter:on
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            // @formatter:off
            clients
                .inMemory()
                    .withClient("clientapp")
                        .authorizedGrantTypes("password","refresh_token")
                        .authorities("USER")
                        .scopes("read", "write")
                        .resourceIds(RESOURCE_ID)
                        .secret("123456");
            // @formatter:on

        }

        @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setTokenStore(this.tokenStore);
            return tokenServices;
        }

    }

}

正如您在上面看到的那样,HttpSecurity在课程中进行了两次扩展,一次扩展WebSecurityConfigurerAdapter,并且在您的班级中为您的Ouath配置扩展ResourceServerConfigurerAdapter

此示例的一部分取自royclarkson的gitHub示例 https://github.com/royclarkson/spring-rest-service-oauth

我不确定你在第二个问题中询问的是什么,你能否澄清一下?