【问题标题】:Access data by curl on Jhistrer 5.10 with OAuth2 and Keyclock使用 OAuth2 和 Keycloak 在 Jhipster 5.10 上通过 curl 访问数据
【发布时间】:2018-08-06 12:19:18
【问题描述】:

我在使用 Keycloak 的 JHipster 5.1.0 和 OAuth2 时遇到问题,如果有人可以帮助我,我将不胜感激。

我创建了一个默认的 jhipster 项目(Monolithic、Angular 6、OAuth 2.0 / OIDC Authentication with Keycloak),并且我没有对生成的代码源进行任何更改。我只配置了 PostgreSQL 并生成了一个实体。

我通过 "./mvnw" 初始化项目,通过 docker-compose -f "src/main/docker/keycloak.yml up" 初始化 Docker 映像,并且我在 Web 上登录并访问了该项目的所有数据。

直到这里一切都好。

但我需要通过 curl 访问数据。这是我的问题。

我使用这个生成了令牌:curl -X POST web_app:web_app@localhost:9080/auth/realms/jhipster/protocol/openid-connect/token -d "username=admin&password=admin&grant_type=password&scope=read"

但我无法使用此令牌访问任何数据。

例如,我尝试使用以下多种变体访问我的数据:curl ocalhost:8080/api/organizacaos -H "Authorization: Bearer $GENERATED_TOKEN_HERE"

但响应总是:

{
  "type" : "https://www.jhipster.tech/problem/problem-with-message",
  "title" : "Unauthorized",
  "status" : 401,
  "detail" : "Full authentication is required to access this resource",
  "path" : "/api/organizacaos",
  "message" : "error.http.401"
}

有人可以帮我吗?

谢谢大家。

【问题讨论】:

  • 由 Keycloak auth 保护的 JHipster API 使用 Cookies 进行身份验证,而不是承载令牌
  • 好的。但是您知道使用带有身份验证的 REST API 访问数据的任何方法吗?

标签: java spring curl jhipster spring-security-oauth2


【解决方案1】:

将 curl 与 JHipster OAuth2 应用程序一起使用并避免处理 cookie 的一种方法是添加一个可以读取您的不记名令牌的 ResourceServer 配置。这是在IonicReact Native JHipster 客户端中完成的,可以在这里应用。

Copy this file 到您的 Java 配置包中,为 Authorization 标头添加 RequestHeaderRequestMatcher 的重要行如下:

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

....

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
....
            .requestMatcher(new RequestHeaderRequestMatcher("Authorization"))
....

然后您可以像您描述的那样获取令牌并向安全 API 发出请求:

# get access token
curl -X POST web_app:web_app@localhost:9080/auth/realms/jhipster/protocol/openid-connect/token -d "username=admin&password=admin&grant_type=password&scope=read"

# request to a secured API
curl localhost:8080/api/account -H "Authorization: Bearer $ACCESS_TOKEN"

【讨论】:

  • 感谢乔恩·鲁德尔。我会改进你的想法并做出我需要的东西。
猜你喜欢
  • 1970-01-01
  • 2020-11-10
  • 2015-07-27
  • 2021-01-25
  • 2021-03-30
  • 1970-01-01
  • 2023-04-04
  • 2011-10-19
  • 1970-01-01
相关资源
最近更新 更多