添加 Spring Oauth2 客户端依赖项后控制器返回默认登录 html 页面
Posted
技术标签:
【中文标题】添加 Spring Oauth2 客户端依赖项后控制器返回默认登录 html 页面【英文标题】:Controllers returning default login html page after adding Spring Oauth2 Client dependency 【发布时间】:2021-10-21 19:04:09 【问题描述】:我是 Spring Security 的新手。我有一个自定义的 oauth 2.0 提供程序。我试图创建一个端点“/test”(不使用 oauth 2.0),它将到达另一个端点 x(x 使用 oauth 2.0)。这是我编写的入门代码-
控制器:
@RestController
public class OAuthController
@GetMapping(value="/test")
public String testing()
System.out.println("running controller");
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForObject("http://localhost:8080/test2", String.class);
//this will be eventually replaced with calling end point x with oauth 2.0
@GetMapping(value="/test2")
public String testing2()
return "Hello from test2";
pom:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
</dependencies>
application.yml:
spring:
security:
oauth2:
client:
registration:
myclient:
client-id: XXX
client-secret: XXX
authorization-grant-type: client_credentials
scope: default
provider: myauthProvider
provider:
myauthProvider:
token-uri: XXX
我的期望是我点击“localhost:8080/test”,我会从端点 x 作为字符串得到响应。但相反,我得到了一个 html 页面 -
为什么我必须登录才能访问“/test”端点?我的期望是“/test”将没有身份验证。如果我删除 spring-boot-starter-oauth2-client 依赖项,那么代码将按预期工作。 如何更改此设置,以便客户端 A 和“/test”之间没有身份验证,但“/test”和端点 x 之间的通信使用 oauth 2.0?
【问题讨论】:
因为 OAuth2 的重点是它委托身份验证。就像当您访问一个网站并要求访问您的 google 联系人时 - 它会将您发送到 google,它会询问您是否希望该网站访问您的联系人。在这种情况下,x 是 google。 @BoristheSpider ,在这种情况下,身份验证发生在某些特定的用户操作上。我怎样才能以这样的方式编写代码,然后“/test”不使用身份验证。只有当我到达终点 x 时才应该使用 Oauth。另外,由于我已经在 yml 中提到了客户端 ID 和密码,它不应该使用该信息自动获取令牌吗? 不幸的是,没有。 Spring Security 不会自动充当 oauth2 客户端并将自身注入到您的 API 调用中。有关如何执行此操作的示例,请参阅oauth2 with webclient sample。请注意,您可以将authorization-grant-type: code
替换为authorization-grant-type: client_credentials
,但授权客户端仍将作用于当前登录的用户。请注意,用户必须默认登录,在您的示例中并非如此。
【参考方案1】:
唯一对我有用的解决方案是删除 spring 安全依赖项并进行 2 个 rest API 调用。
-
在第一次休息调用中,我点击了自定义 oauth 提供者令牌 url,传递了客户端 ID、秘密。我在响应中获得了访问令牌。
之后我到达终点 x 并在标头中传递了令牌
手动。
【讨论】:
以上是关于添加 Spring Oauth2 客户端依赖项后控制器返回默认登录 html 页面的主要内容,如果未能解决你的问题,请参考以下文章
Tomcat 7 SEVERE:在 pom 中将 spring-data-jpa 添加到依赖项后,由于先前的错误,上下文 [] 启动失败
升级 spring 依赖项后出现错误 A JTA EntityManager 无法使用 getTransaction()
Spring Security Oauth2 整合单点登录简易demo
升级Spring依赖项后获取错误A JTA EntityManager无法使用getTransaction()
Spring/OAuth2 错误 - InsufficientAuthenticationException,没有客户端身份验证。尝试添加适当的身份验证过滤器