Spring Security OAuth - 如何启用访问不同资源的私有或公共访问令牌?

时间:2015-07-23 18:42:14

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

我有两个终点。

/foo - 是一个内部(半私有)端点。仅允许配置的客户端。 (不需要userName和凭据;但clientID就足够了)

/greetings - 是一个私人端点。仅允许客户端和用户配置。 (需要clientID,用户名和密码)

这是配置。

@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
                .authorizeRequests()
                    .antMatchers("/users").hasRole("ADMIN")
                    .antMatchers("/greeting").authenticated()
                    .antMatchers("/foo").authenticated();
            // @formatter:on
        }

    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends
            AuthorizationServerConfigurerAdapter {

        private TokenStore tokenStore = new InMemoryTokenStore();

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

        @Autowired
        private CustomUserDetailsService userDetailsService;

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

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

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

        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception
        {
           oauthServer.checkTokenAccess("permitAll()");
        }

    }

}

这是控制器

@RestController
public class GreetingController {

    private static final String template = "Hello, %s! your password is %s";

    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@AuthenticationPrincipal User user) {
        return new Greeting(counter.incrementAndGet(), String.format(template, user.getName(),user.getPassword()));
    }

    @RequestMapping("/foo")
    public String foo(@AuthenticationPrincipal User user) {
        System.out.println(user==null);
        return "you are permitted here";
    }

}

我无法在没有任何令牌的情况下访问http://localhost:9001/foo。 所以当我尝试使用下面的curl获取访问令牌时(注意我没有传递用户名和密码,只传递了client_id和client_secret)

13 C url -X POST -vu clientapp:123456 http://localhost:9001/oauth/token -H "Accept: application/json" -d "grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp"

我收到此错误

{"error":"invalid_grant","error_description":"Bad credentials"}

我的配置有问题。我是使用Spring安全OAuth的初学者。非常感谢这里的任何帮助。

感谢

1 个答案:

答案 0 :(得分:0)

我认为你错了grant_type ......

curl -X POST -vu clientapp:123456 http://localhost:9001/oauth/token -H "Accept: application/json" -d "grant_type=client_credentials&scope=read%20write&client_secret=123456&client_id=clientapp"

另据我记得,你不应该在请求的标题和正文中复制client_idclient_secret ..只有标题应该足够了