【发布时间】:2016-08-15 02:27:47
【问题描述】:
我正在尝试使用 Spring Boot 1.2.2 为 REST API 运行一个小型概念验证,并使用 OAuth2 进行保护。为此,我创建了两个项目,一个用于身份验证服务器,另一个用于 REST 服务。
运行项目时,一切正常。我从身份验证服务器获取了一个令牌,然后使用该令牌,我设法调用了该服务并获得了预期的结果。
当我尝试验证服务中的范围时会出现此问题。只要我添加该行:
@PreAuthorize("#oauth2.hasScope('webshop')")
为我服务,在代码中:
@RestController
public class ProductService {
@RequestMapping("/product/{productId}")
@PreAuthorize("#oauth2.hasScope('webshop')")
public Product getProduct(@PathVariable int productId) {
return new Product(productId, "name", 123);
}
}
我收到此回复:
{
"error": "insufficient_scope",
"error_description": "Insufficient scope for this resource",
"scope": "webshop"
}
认证服务器配置为:
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("acme")
.secret("acmesecret")
.authorizedGrantTypes("authorization_code", "refresh_token", "implicit", "password", "client_credentials")
.scopes("webshop");
}
}
这是获取令牌的实际调用:
juan@ubuntu:~/ms/core/product-service$ curl -s acme:acmesecret@localhost:9999/uaa/oauth/token -d grant_type=client_credentials -d scope=webshop
{
"access_token": "ac3a9768-4ebb-44e3-a49f-21e2f117d0b4",
"token_type": "bearer",
"expires_in": 43199,
"scope": "webshop"
}
然后,调用服务:
juan@ubuntu:~/ms/core/product-service$ TOKEN=ac3a9768-4ebb-44e3-a49f-21e2f117d0b4
juan@ubuntu:~/ms/core/product-service$ curl 'http://localhost:8080/product/32' -H "Authorization: Bearer $TOKEN" -s
{
"error": "insufficient_scope",
"error_description": "Insufficient scope for this resource",
"scope": "webshop"
}
我觉得我只是因为缺乏概念而错过了一些简单的东西。如果客户端是在内存中创建的,应该允许做“网店”,并且成功生成了token,为什么会产生错误?
提前感谢您指出一些方向或帮助。
【问题讨论】:
标签: api rest security spring-security-oauth2