我试图让谷歌OAuth2.0与java spring Boot WebAPI一起工作,我目前从spring-security文档中引用它
在将依赖项添加到pom.xml之后,每个请求似乎都得到了保护
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
和configuration.java如下
@EnableWebSecurity
@Configuration
@EnableMethodSecurity
public class SecurityConfiguration{
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authz) -> authz
.anyRequest().authenticated()
)
.httpBasic(withDefaults());
return http.build();
}
}
添加所有这部分后,我所有的API请求仍然无法访问,即使我从谷歌OAuth获得了正确的承载令牌,在请求过程中作为认证头,它总是返回401未经授权的 Postman ,想知道我错过了什么,导致程序拒绝所有请求?
API代码如下
@RequestMapping(value = "testauth", method = RequestMethod.GET)
public ResponseEntity<Object> createTask() {
String result = "Hellow World";
return new ResponseEntity<>(result, HttpStatus.OK);
}
1条答案
按热度按时间6ovsh4lw1#
对于
http.httpBasic(withDefaults())
,您需要使用Basic
授权头对请求进行授权。带有Bearer
授权头的请求是未经授权的,这是完全可以预料的(我相信您配置了Postman来发送带有Bearer
授权的请求,其中包含来自Google的访问令牌)。在OAuth2请求中,
Bearer
授权头(OAuth2资源服务器,spring-boot-starter-oauth2-resource-server
简化了配置)oauth2Login
的OAuth2客户端,spring-boot-starter-oauth2-client
简化了配置)REST API通常被配置为资源服务器(使用访问令牌授权的请求,就像您可能正在尝试做的那样),而不是客户端(使用会话授权的请求,而不是访问令牌)。
坏消息是,Google授权服务器被设计用于Google资源服务器(Google API),而不是您的。您可以绕过它(使用
userinfo
端点作为内省端点),但代价是性能非常差。如果你想让事情正常进行,你应该设置一个自己的授权服务器,它将联合谷歌身份。市场上有很多具有这种“使用Google登录”功能的选项,无论是“本地”(Keycloak是一个着名的示例)还是在云中(Auth0,Okta,Amazon Cognito等)。您也可以使用
spring-authorization-server
构建自己的,但这需要更多的工作(并且需要相当多的Web安全知识,特别是OAuth2和OIDC)。有关更多OAuth2背景和OAuth2的Spring Security配置,请参阅我的教程和official documentation。