springdoc-openapi-ui Поток кода авторизации OAuth 2.0 с PKCE
Я использую чванство с springdoc-openapi-ui-1.4.3
@SecurityRequirement(name = "security_auth")
public class ProductController {}
Установка схемы безопасности
@SecurityScheme(name = "security_auth", type = SecuritySchemeType.OAUTH2,
flows = @OAuthFlows(authorizationCode = @OAuthFlow(
authorizationUrl = "${springdoc.oAuthFlow.authorizationUrl}"
, tokenUrl = "${springdoc.oAuthFlow.tokenUrl}",scopes = {
@OAuthScope(name = "IdentityPortal.API", description = "IdentityPortal.API")})))
public class OpenApiConfig {}
Конфигурация безопасности
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {// @formatter:off
http
.authorizeRequests()
.antMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html")
.permitAll()
.antMatchers(HttpMethod.GET, "/user/info", "/api/foos/**")
.hasAuthority("SCOPE_read")
.antMatchers(HttpMethod.POST, "/api/foos")
.hasAuthority("SCOPE_write")
.anyRequest()
.authenticated()
.and()
.oauth2ResourceServer()
.jwt();
}
}
С зависимостями
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
implementation 'org.springdoc:springdoc-openapi-ui:1.4.3'
implementation 'org.springdoc:springdoc-openapi-security:1.4.3'
implementation "org.springframework.boot:spring-boot-starter-security"
Настройка конфигурации
spring:
profiles:
active: dev
####### resource server configuration properties
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://localhost:5001
jwk-set-uri: https://localhost:5001/connect/token
springdoc:
swagger-ui:
oauth:
clientId: Local
usepkcewithauthorizationcodegrant: true
oAuthFlow:
authorizationUrl: https://localhost:5001
tokenUrl: https://localhost:5001/connect/token
В пользовательском интерфейсе swagger clientId пуст и присутствует секрет клиента, для кода авторизации + секрет клиента потока PKCE не должен присутствовать
2 ответа
Синтаксис вашего свойства
usepkcewithauthorizationcodegrant
не является правильным:
Вот подходящее свойство для PKCE:
springdoc.swagger-ui.oauth.use-pkce-with-authorization-code-grant=true
Чтобы заполнить идентификатор клиента, просто используйте:
springdoc.swagger-ui.oauth.client-id=yourSPAClientId
За ваше замечание о существующем секретном поле, которое можно скрыть. Похоже, это улучшенный интерфейс swagger-ui.
Вы должны отправить улучшение в проект swagger-ui:
Вы уже давно не задавали этот вопрос, но я отвечу на вопросы других пользователей. Основная проблема - неправильная конфигурация. PKCE является производным от неявного потока (или, точнее, оба предназначены для общедоступных клиентов). Поэтому измените конфигурацию безопасности на:
@SecurityScheme(name = "security_auth", type = SecuritySchemeType.OAUTH2,
flows = @OAuthFlows(implicit = @OAuthFlow(
authorizationUrl = "${springdoc.oAuthFlow.authorizationUrl}"
, tokenUrl = "${springdoc.oAuthFlow.tokenUrl}")))
public class OpenApiConfig {}
Это приведет к отсутствию client_secret (следовательно, он не нужен). Я удалил области видимости из аннотации, потому что у меня есть ощущение, что вы смешиваете области действия с client_id (его настройка описана ниже).
Если вы хотите использовать PKCE вместо чистого неявного атрибута правильного набора (как указано в @brianbro) как:
springdoc.swagger-ui.oauth.use-pkce-with-authorization-code-grant=true
И последнее, что не менее важно, если вы хотите предварительно заполнить конфигурацию использования client_id:
springdoc.swagger-ui.oauth.client-id=YourClientId