LoginSignup
0
0

More than 1 year has passed since last update.

SpringBoot SwaggerUI(JWT SpringSecurity付)の実装

Last updated at Posted at 2023-01-24

概要

SpringBootでSwaggerUIの実装をします。
SwaggerUIはAPIをドキュメンテーション化ができるツールです。

開発環境

OS:windows10
IDE:IntelliJ Community
spring-boot-starter-parent 2.75
java : 11

実装

Swaggerの導入

pom.xmlにswaggerを追加する

pom.xml
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-boot-starter</artifactId>
			<version>3.0.0</version>
		</dependency>

SpringSecurityでSwaggerのアクセス許可をする

WebSecurity.java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        http.antMatchers("/v2/api-docs/**").permitAll()
        return http.build();
    }
}

SpringBoot起動後 
http://localhost:5000/v2/api-docs
にアクセスできることを確認。
アクセス成功時の様子
image.png

Swagger UIを導入する。

SwaggerのConfigファイルを作成する。

Docketクラスのメソッドを追加する

SwaggerConfig.java
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

SpringSecurityでSwaggerUIにアクセスできるようにする。

WebSecurity.java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        http.antMatchers("/v2/api-docs/**").permitAll()
+            .antMatchers("/swagger-ui/**").permitAll()
+            .antMatchers("/swagger-resources/**").permitAll()
+            .antMatchers("/swagger-ui.html").permitAll()
+            .antMatchers("/webjars/**").permitAll()
        return http.build();
    }
}

SpringBoot起動後
http://localhost:5000/swagger-ui/
にアクセスしてSwaggerUIにアクセスできることを確認する。
以下成功時の画像
image.png

JWT認証を反映させる

JWTファイルに対応できるようにSwaggerのConfigファイルにコードを追加します。

SwaggerSecurity.java
@Configuration
public class SwaggerConfig {
+    public static final String AUTHORIZATION_HEADER = "Authorization";
+    private ApiKey apiKey(){
+        return new ApiKey("JWT",AUTHORIZATION_HEADER, "header");
+    }
+    

    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)
+               .securityContexts(Arrays.asList(securityContext())) // about JWT
+               .securitySchemes(Arrays.asList(apiKey()))           // about JWT
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
    // about JWT
+    private SecurityContext securityContext(){
+        return SecurityContext.builder().securityReferences(defaultAuth()).build();
+    }

    // about JWT
+    private List<SecurityReference> defaultAuth(){
+        AuthorizationScope authorizationScope = new +AuthorizationScope("global","accessEverything");
+        AuthorizationScope[]  authorizationScopes = new AuthorizationScope[1];
+        authorizationScopes[0] = authorizationScope;
+        return Arrays.asList(new SecurityReference("JWT",authorizationScopes));
    }
}

再度SwaggerUIを開くと、アイコンが追加されていることを確認できる。
以下画像
image.png

JWTの動きを確認する。

SwaggerUIで以下の動きを再現します。
1.ログインする
2.ログイン成功後 買い物かごの情報を取得する。

Loginする

Emailアドレス:aaaba@gmail.com
パスワード:test
でログインします。ログイン成功後JWTトークンがhttpResponseで返ってきます。
以下その時の様子。
SwaggerUI_Login.gif

Login成功後、買い物かごの情報を取得する。

Loginの際に得たJWTトークンを使って認可認証が必要なAPIを使います。

Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhYWFiYUBnbWFpbC5jb20iLCJpYXQiOjE2NzQ1MjkwMTQsImV4cCI6MTY3NTEzMzgxNH0.tBHIFjU5yQYdpK7ISOlZS_txYCG1VJy6PKBwSac-H_Fs0Q9YGqKnUAFrm7jOduxJCQvsLby9kGjmXizqGPZBRA

以下その時の様子。
SwaggerUI_GetData.gif

参考資料

Section22 Swagger REST Api Documentation

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0