Swagger中的Keycloak集成

问题描述 投票:34回答:3

我有一个Keycloak保护的后端,我想通过swagger-ui访问。 Keycloak提供了oauth2隐式和访问代码流,但我无法使其工作。目前,Keycloak的文档缺乏关于swagger.json中的authorizationUrl和tokenUrl应该使用哪个url。

Keycloak中的每个领域都通过访问http://keycloak.local/auth/realms/REALM/.well-known/openid-configuration提供了大量的配置网址

此外,我试图通过添加以下行直接在swagger-ui index.html中集成keycloak js-client:

<script src="keycloak/keycloak.js"></script>
<script>
  var keycloak = Keycloak('keycloak.json');
    keycloak.init({ onLoad: 'login-required' })
      .success(function (authenticated) {
        console.log('Login Successful');
        window.authorizations.add("oauth2", new ApiKeyAuthorization("Authorization", "Bearer " + keycloak.token, "header"));
      }).error(function () {
        console.error('Login Failed');
        window.location.reload();
      }
    );
 </script>

“登录成功”后我也尝试了类似的东西

swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer " + keycloak.token, "header"));

但它也行不通。

有什么建议我如何在swagger中集成keycloak auth?

oauth swagger swagger-ui keycloak jboss-tools
3个回答
6
投票

Swagger-ui可以使用implicit身份验证模式与keycloak集成。你可以在swagger-ui上设置oauth2,这样它就会要求你进行身份验证,而不是直接给swagger-ui提供访问令牌。

第一件事,你的招摇需要引用安全定义,如:

"securityDefinitions": {
    "oauth2": {
        "type":"oauth2",
        "authorizationUrl":"http://172.17.0.2:8080/auth/realms/master/protocol/openid-connect/auth",
        "flow":"implicit",
        "scopes": {
            "openid":"openid",
            "profile":"profile"
        }
    }
}

然后,你摇摆 - 你需要引用一些其他参数:使用纯js,你可以在index.html中使用

const ui = SwaggerUIBundle({ ...} );

ui.initOAuth({
    clientId: "test-uid",
    realm: "Master",
    appName: "swagger-ui",
    scopeSeparator: " ",
    additionalQueryStringParams: {"nonce": "132456"}
})

在这段代码中,

  • authorizationUrl是您的keycloak领域的授权终点
  • 范围是您可以根据自己的需求设置的
  • clientId是一个在keycloak领域使用implicit模式进行参数化的客户端
  • 附加参数nonce应该是随机的,但是swagger-ui还没有使用它。

如果你想在Spring-boot上做所有这些,我在这里添加一个例子:

在这个框架中,你将主要使用Springfox的swagger和swagger-ui web-jar。这是通过添加依赖项来完成的:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>

通过在主类上添加注释swagger2来启用Swagger:

@SpringBootApplication
@EnableSwagger2
public class TestSpringApplication {
    ...

然后你可以像这样设置一个Configuration类:

@Configuration
public class SwaggerConfigurer {

    @Bean
    public SecurityConfiguration securityConfiguration() {

        Map<String, Object> additionalQueryStringParams=new HashMap<>();
        additionalQueryStringParams.put("nonce","123456");

        return SecurityConfigurationBuilder.builder()
            .clientId("test-uid").realm("Master").appName("swagger-ui")
            .additionalQueryStringParams(additionalQueryStringParams)
            .build();
    }

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.testspring"))
            .paths(PathSelectors.any())
            .build().securitySchemes(buildSecurityScheme()).securityContexts(buildSecurityContext());
    }

    private List<SecurityContext> buildSecurityContext() {
        List<SecurityReference> securityReferences = new ArrayList<>();

        securityReferences.add(SecurityReference.builder().reference("oauth2").scopes(scopes().toArray(new AuthorizationScope[]{})).build());

        SecurityContext context = SecurityContext.builder().forPaths(Predicates.alwaysTrue()).securityReferences(securityReferences).build();

        List<SecurityContext> ret = new ArrayList<>();
        ret.add(context);
        return ret;
    }

    private List<? extends SecurityScheme> buildSecurityScheme() {
        List<SecurityScheme> lst = new ArrayList<>();
        // lst.add(new ApiKey("api_key", "X-API-KEY", "header"));

        LoginEndpoint login = new LoginEndpointBuilder().url("http://172.17.0.2:8080/auth/realms/master/protocol/openid-connect/auth").build();

        List<GrantType> gTypes = new ArrayList<>();
        gTypes.add(new ImplicitGrant(login, "acces_token"));

        lst.add(new OAuth("oauth2", scopes(), gTypes));
        return lst;
    }

    private List<AuthorizationScope> scopes() {
        List<AuthorizationScope> scopes = new ArrayList<>();
        for (String scopeItem : new String[]{"openid=openid", "profile=profile"}) {
            String scope[] = scopeItem.split("=");
            if (scope.length == 2) {
                scopes.add(new AuthorizationScopeBuilder().scope(scope[0]).description(scope[1]).build());
            } else {
                log.warn("Scope '{}' is not valid (format is scope=description)", scopeItem);
            }
        }

        return scopes;
    }
}

您可以在此代码中更新许多内容。这与以前大致相同:

  • nonce应该是一个随机的东西(swagger-ui不使用它)
  • clientId,您需要根据您在keycloak中设置的客户端进行相应设置
  • basePackage:您需要设置所有控制器所在的包
  • 如果需要api-key,可以启用它并将其添加到安全方案列表中
  • LoginEndpoint:这需要是你keycloak领域的授权终点
  • scopeItems:您要进行此身份验证的范围。

它将生成与以前相同的东西:更新swagger以添加securityDefinition并使swagger-UI获取clientId,nonce,...的参数


5
投票

在过去的两天里,我一直在努力解决这个问题。终于为那些无法解决的人找到了一个有效的解决方案。

pom.hml

    ...
    <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-spring-security-adapter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-spring-boot-starter</artifactId>
    </dependency>
    ...

在主类上启用Swagger

...    
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
@EnableAsync
@EnableCaching
public class MainApplication {
  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(MainApplication.class);
    app.run(args);
  }
}

swagger config.Java

package com.XXX.XXXXXXXX.app.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.AuthorizationCodeGrantBuilder;
import springfox.documentation.builders.OAuthBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Arrays;

import static springfox.documentation.builders.PathSelectors.regex;

/*
 * Setting up Swagger for spring boot
 * https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

 @Value("${keycloak.auth-server-url}")
 private String AUTH_SERVER;

 @Value("${keycloak.credentials.secret}")
 private String CLIENT_SECRET;

 @Value("${keycloak.resource}")
 private String CLIENT_ID;

 @Value("${keycloak.realm}")
 private String REALM;

 private static final String OAUTH_NAME = "spring_oauth";
 private static final String ALLOWED_PATHS = "/directory_to_controllers/.*";
 private static final String GROUP_NAME = "XXXXXXX-api";
 private static final String TITLE = "API Documentation for XXXXXXX Application";
 private static final String DESCRIPTION = "Description here";
 private static final String VERSION = "1.0";

 @Bean
 public Docket taskApi() {
   return new Docket(DocumentationType.SWAGGER_2)
    .groupName(GROUP_NAME)
    .useDefaultResponseMessages(true)
    .apiInfo(apiInfo())
    .select()
    .paths(regex(ALLOWED_PATHS))
    .build()
    .securitySchemes(Arrays.asList(securityScheme()))
    .securityContexts(Arrays.asList(securityContext()));
 }

 private ApiInfo apiInfo() {
   return new 
     ApiInfoBuilder().title(TITLE).description(DESCRIPTION).version(VERSION).build();
 }

 @Bean
 public SecurityConfiguration security() {
   return SecurityConfigurationBuilder.builder()
    .realm(REALM)
    .clientId(CLIENT_ID)
    .clientSecret(CLIENT_SECRET)
    .appName(GROUP_NAME)
    .scopeSeparator(" ")
    .build();
 }

 private SecurityScheme securityScheme() {
   GrantType grantType =
    new AuthorizationCodeGrantBuilder()
        .tokenEndpoint(new TokenEndpoint(AUTH_SERVER + "/realms/" + REALM + "/protocol/openid-connect/token", GROUP_NAME))
        .tokenRequestEndpoint(
            new TokenRequestEndpoint(AUTH_SERVER + "/realms/" + REALM + "/protocol/openid-connect/auth", CLIENT_ID, CLIENT_SECRET))
        .build();

SecurityScheme oauth =
    new OAuthBuilder()
        .name(OAUTH_NAME)
        .grantTypes(Arrays.asList(grantType))
        .scopes(Arrays.asList(scopes()))
        .build();
return oauth;
 }

 private AuthorizationScope[] scopes() {
AuthorizationScope[] scopes = {
  new AuthorizationScope("user", "for CRUD operations"),
  new AuthorizationScope("read", "for read operations"),
  new AuthorizationScope("write", "for write operations")
};
return scopes;
}

private SecurityContext securityContext() {
return SecurityContext.builder()
    .securityReferences(Arrays.asList(new SecurityReference(OAUTH_NAME, scopes())))
    .forPaths(PathSelectors.regex(ALLOWED_PATHS))
    .build();
 }
}

从终端运行“mvnw spring-boot:run”

打开浏览器并点击http://localhost:[port]/[app_name]/swagger-ui.html

单击授权按钮:Swagger Authorize Button

这应该提供一个模式来确认您的keycloak设置。

再次单击“授权”按钮。您应该被重定向到登录屏幕。

输入并确认凭据后,您将被重定向回Swagger-UI完全身份验证。


0
投票

使用隐式流,OpenAPI 3.0模板的Swagger-ui + Keycloak(或任何其他OAuth2提供程序):

components:
  ...
   securitySchemes:
    my_auth_whatever:
      type: oauth2
      flows:
        implicit:
          authorizationUrl: https://MY-KEYCLOAK-HOST/auth/realms/MY-REALM-ID/protocol/openid-connect/auth
          scopes: {}
  ...
security:
  - my_auth_whatever: []

确保在您使用的客户端的Keycloak设置中启用了隐式流。

一个缺点是,当点击Swagger UI中的“授权”按钮时,仍然要求用户在模态中使用client_id。用户输入的值可以通过将query param ?client_id=YOUR-CLIENT-ID添加到authorizationUrl来覆盖,但它有点肮脏的黑客并且模式仍然显示给用户。在docker中运行swagger-ui时,可以向容器提供OAUTH_CLIENT_ID env var以设置模式的默认client_id值。对于非docker部署,请参阅@wargre的方法,更改index.html(不确定是否有更好的方法)。

对于SwaggerAPI(OpenAPI 2.0)示例,请参阅@ wargre的答案中的第一个代码片段以及此doc:https://swagger.io/docs/specification/2-0/authentication/

© www.soinside.com 2019 - 2024. All rights reserved.