Skip to content

Commit c06a5ff

Browse files
committed
feat(swagger): implement swagger ui
1 parent e4b1ff5 commit c06a5ff

File tree

6 files changed

+90
-11
lines changed

6 files changed

+90
-11
lines changed

pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,11 @@
102102
<groupId>org.flywaydb</groupId>
103103
<artifactId>flyway-database-postgresql</artifactId>
104104
</dependency>
105+
<dependency>
106+
<groupId>org.springdoc</groupId>
107+
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
108+
<version>2.8.5</version>
109+
</dependency>
105110
</dependencies>
106111

107112
<build>

src/main/java/com/andriawan/andresource/config/Security.java

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,12 @@
66
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
77
import com.nimbusds.jose.jwk.source.JWKSource;
88
import com.nimbusds.jose.proc.SecurityContext;
9-
109
import java.security.interfaces.RSAPrivateKey;
1110
import java.security.interfaces.RSAPublicKey;
12-
1311
import org.springframework.beans.factory.annotation.Value;
1412
import org.springframework.context.annotation.Bean;
1513
import org.springframework.context.annotation.Configuration;
14+
import org.springframework.core.annotation.Order;
1615
import org.springframework.security.config.Customizer;
1716
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
1817
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@@ -42,22 +41,32 @@ public class Security {
4241
@Value("${auth.sample.password}")
4342
private String samplePassword;
4443

45-
private String[] publicRoute = {
46-
"/api/v1/auth/login",
47-
"/api/v1/auth/token/refresh"
48-
};
44+
private String[] publicRoute = {"/v3/api-docs/*", "/v3/api-docs", "/swagger-ui/*"};
45+
46+
private String loginRoute = "/api/v1/auth/login";
4947

5048
@Bean
5149
public InMemoryUserDetailsManager sampleUser() {
52-
UserDetails user = User.withUsername(sampeUsername)
53-
.password("{noop}".concat(samplePassword)).build();
50+
UserDetails user =
51+
User.withUsername(sampeUsername).password("{noop}".concat(samplePassword)).build();
5452
return new InMemoryUserDetailsManager(user);
5553
}
5654

5755
@Bean
58-
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
56+
@Order(1)
57+
public SecurityFilterChain loginFilterChain(HttpSecurity http) throws Exception {
5958
return http.httpBasic(Customizer.withDefaults())
60-
.authorizeHttpRequests(
59+
.securityMatcher(loginRoute)
60+
.csrf(crsf -> crsf.disable())
61+
.sessionManagement(
62+
session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
63+
.build();
64+
}
65+
66+
@Bean
67+
@Order(2)
68+
public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
69+
return http.authorizeHttpRequests(
6170
request ->
6271
request.requestMatchers(publicRoute).permitAll().anyRequest().authenticated())
6372
.csrf(crsf -> crsf.disable())
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package com.andriawan.andresource.config;
2+
3+
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
4+
import io.swagger.v3.oas.annotations.security.SecurityScheme;
5+
import io.swagger.v3.oas.models.OpenAPI;
6+
import io.swagger.v3.oas.models.info.Info;
7+
import io.swagger.v3.oas.models.servers.Server;
8+
import java.util.Map;
9+
import org.springframework.beans.factory.annotation.Autowired;
10+
import org.springframework.beans.factory.annotation.Value;
11+
import org.springframework.context.annotation.Bean;
12+
import org.springframework.context.annotation.Configuration;
13+
14+
@Configuration
15+
@SecurityScheme(
16+
name = "jwt",
17+
type = SecuritySchemeType.HTTP,
18+
bearerFormat = "JWT",
19+
scheme = "bearer")
20+
@SecurityScheme(name = "basicAuth", type = SecuritySchemeType.HTTP, scheme = "basic")
21+
public class Swagger {
22+
23+
@Autowired GitInfo gitInfo;
24+
25+
@Value("${spring.application.name}")
26+
String appName;
27+
28+
@Value("${app.description}")
29+
String appDesc;
30+
31+
@Value("${app.summary}")
32+
String appSummary;
33+
34+
@Bean
35+
public OpenAPI custom() {
36+
Server currentServer = new Server();
37+
currentServer.url("/");
38+
currentServer.setDescription("current");
39+
String description =
40+
String.format(
41+
"%s. Last Update: %s. Last commit id: %s",
42+
appDesc, gitInfo.lastUpdate, gitInfo.gitCommitHash);
43+
Info info =
44+
new Info()
45+
.version(gitInfo.getVersion())
46+
.title(appName)
47+
.summary(appSummary)
48+
.extensions(Map.of("test", "string"))
49+
.description(description);
50+
return new OpenAPI().addServersItem(currentServer).info(info);
51+
}
52+
}

src/main/java/com/andriawan/andresource/controller/AuthController.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.andriawan.andresource.controller;
22

33
import com.andriawan.andresource.service.TokenService;
4+
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
45
import java.util.Map;
56
import org.springframework.beans.factory.annotation.Autowired;
67
import org.springframework.http.ResponseEntity;
@@ -14,11 +15,13 @@
1415
public class AuthController {
1516
@Autowired private TokenService tokenService;
1617

18+
@SecurityRequirement(name = "basicAuth")
1719
@PostMapping("/login")
1820
public ResponseEntity<Map<String, String>> authenticate(Authentication authentication) {
1921
return ResponseEntity.ok(tokenService.generateToken(authentication));
2022
}
2123

24+
@SecurityRequirement(name = "jwt")
2225
@PostMapping("/token/refresh")
2326
public ResponseEntity<Map<String, String>> refreshToken(Authentication authentication) {
2427
return ResponseEntity.ok(tokenService.generateToken(authentication));

src/main/java/com/andriawan/andresource/controller/UserController.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import com.andriawan.andresource.entity.User;
44
import com.andriawan.andresource.repository.UserRepository;
5+
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
6+
import java.security.Principal;
57
import java.util.List;
68
import org.springframework.beans.factory.annotation.Autowired;
79
import org.springframework.http.ResponseEntity;
@@ -10,12 +12,13 @@
1012
import org.springframework.web.bind.annotation.RestController;
1113

1214
@RestController
15+
@SecurityRequirement(name = "jwt")
1316
@RequestMapping("/api/v1")
1417
public class UserController {
1518
@Autowired private UserRepository userRepository;
1619

1720
@GetMapping("/users")
18-
public ResponseEntity<List<User>> getAllUser() {
21+
public ResponseEntity<List<User>> getAllUser(Principal principal) {
1922
List<User> users = userRepository.findAll();
2023
return ResponseEntity.ok(users);
2124
}

src/main/resources/application.properties

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,10 @@ jwt.refresh.expired.seconds=${JWT_REFRESH_EXPIRED_SECONDS:600}
2626
# AUTH
2727
auth.sample.user=${AUTH_SAMPLE_USER:admin}
2828
auth.sample.password=${AUTH_SAMPLE_USER:password}
29+
30+
# APP
31+
app.description=${APP_DESCRIPTION:Sample Demo Apps}
32+
app.summary=${APP_SUMMARY:Sample Summary}
33+
34+
# Swagger
35+
springdoc.swagger-ui.path=${SWAGGER_UI_PATH:}

0 commit comments

Comments
 (0)