java - 无效令牌不包含资源 id (oauth2-resource)
问题描述
我正在学习 OAuth2,但我在 client_credentials 授权配置方面遇到了问题。这是一些客户端-服务器示例。
客户端(8080):
@SpringBootApplication
@EnableOAuth2Client
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
@Bean
@ConfigurationProperties("security.oauth2.client")
public ClientCredentialsResourceDetails oAuthDetails() {
return new ClientCredentialsResourceDetails();
}
@Bean
public OAuth2RestTemplate restTemplate() {
return new OAuth2RestTemplate(oAuthDetails());
}
}
@Configuration
public class ClientSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll();
}
}
@Controller
public class ClientController {
@Autowired
private OAuth2RestTemplate template;
@GetMapping("/getServer")
public String get() {
template.getForEntity("http://localhost:8081/endpoint", String.class);
return "index.html";
}
}
资源服务器端(8081):
@SpringBootApplication
@EnableResourceServer
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
@Configuration
public class ServerSecurity extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/actuator/**").permitAll();
}
}
@RestController
public class ServerController {
@GetMapping("/endpoint")
public ResponseEntity<String> respond() {
return new ResponseEntity<>("", HttpStatus.OK);
}
}
当我点击客户端的 /getServer 时,我得到了这个异常:
org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException: Invalid token does not contain resource id (oauth2-resource)
如果我删除 ServerSecurity,ClientController 可以正常工作而不会引发异常,但服务器的执行器/运行状况会因 401 而失败。
可能有什么问题?
附加信息:
客户的 yml:
server:
port: 8080
security:
oauth2:
client:
grant-type: client_credentials
clientId: __data__
clientSecret: __data__
accessTokenUri: https://dev-410899.oktapreview.com/oauth2/default/v1/token
scope: web_app
resource:
id: oauth2-resource
服务器的 yml:
server:
port: 8081
security:
oauth2:
client:
clientId: __data__
clientSecret: __data__
resource:
tokenInfoUri: https://dev-410899.oktapreview.com/oauth2/default/v1/introspect
解决方案
默认的 OAuth2 资源服务器 ID 是oauth2-resource
. (检查ResourceServerSecurityConfigurer
)。您可以设置自定义资源服务器 ID:
@Override
public void configure(ResourceServerSecurityConfigurer oauthServer) {
oauthServer
.resourceId("your resource id");
}
在发出令牌时,您必须确保让您的 client_credentials 用户访问正确的资源服务器 ID。
推荐阅读
- oracle - 使用序列构建 Oracle 视图
- css - 正文中断布局上的等宽字体
- java - 使用 Java 和 Python 的 uuencoded 文件之间的区别
- sql-server - 如何根据 json 中的 id 从表中删除行
- php - 使用 PHP SoapClient 将多个值发送到同一个字段
- python - AttributeError:模块“pydotplus”没有属性“节点”
- python - 未定义字符的 Unicode 编码错误
- django - Django - 空表单无法保存在数据库中
- c++ - 使用命名空间的 QT 测试
- java - 是否可以先应用 maven 叠加层,然后开始构建应用了叠加层的项目?