-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
SDIT-1336 Add in Spring Security by including the library hmpps-kotli…
…n-spring-boot-starter
- Loading branch information
1 parent
3252f67
commit 56e464e
Showing
16 changed files
with
381 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
16 changes: 16 additions & 0 deletions
16
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppstemplatepackagename/TimeResource.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package uk.gov.justice.digital.hmpps.hmppstemplatepackagename | ||
|
||
import org.springframework.security.access.prepost.PreAuthorize | ||
import org.springframework.web.bind.annotation.GetMapping | ||
import org.springframework.web.bind.annotation.RequestMapping | ||
import org.springframework.web.bind.annotation.RestController | ||
import java.time.LocalDateTime | ||
|
||
@RestController | ||
@RequestMapping("/time") | ||
class TimeResource { | ||
|
||
@PreAuthorize("hasRole('TEMPLATE_EXAMPLE')") | ||
@GetMapping | ||
fun getTime() = "${LocalDateTime.now()}" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
82 changes: 82 additions & 0 deletions
82
...in/uk/gov/justice/digital/hmpps/hmppstemplatepackagename/config/WebClientConfiguration.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
package uk.gov.justice.digital.hmpps.hmppstemplatepackagename.config | ||
|
||
import org.springframework.beans.factory.annotation.Value | ||
import org.springframework.context.annotation.Bean | ||
import org.springframework.context.annotation.Configuration | ||
import org.springframework.http.client.reactive.ReactorClientHttpConnector | ||
import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager | ||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager | ||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder | ||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService | ||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository | ||
import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction | ||
import org.springframework.web.reactive.function.client.WebClient | ||
import reactor.netty.http.client.HttpClient | ||
import java.time.Duration | ||
import kotlin.apply as kotlinApply | ||
|
||
@Configuration | ||
class WebClientConfiguration( | ||
@Value("\${api.base.url.oauth}") val oauthApiBaseUri: String, | ||
@Value("\${api.health-timeout:2s}") val healthTimeout: Duration, | ||
@Value("\${api.timeout:90s}") val timeout: Duration, | ||
) { | ||
@Bean | ||
fun oauthApiHealthWebClient(builder: WebClient.Builder): WebClient = builder.healthWebClient(oauthApiBaseUri, healthTimeout) | ||
|
||
/** | ||
* TODO | ||
* Once you have a client registration defined in properties `spring.security.client.registration` then you'll | ||
* need to uncomment this @Bean and create both a health and authorized web client. | ||
* | ||
* e.g. if your client registration config looks like this (registrationId is `prison-api`): | ||
* ``` | ||
* spring: | ||
* security: | ||
* client: | ||
* registration: | ||
* prison-api: | ||
* provider: hmpps-auth | ||
* client-id: ${prison-api.client.id} | ||
* client-secret: ${prison-api.client.secret} | ||
* authorization-grant-type: client_credentials | ||
* scope: read | ||
* ``` | ||
* Then you need to create web clients in this class as follows: | ||
* ``` | ||
* @Bean | ||
* fun prisonApiHealthWebClient(builder: WebClient.Builder): WebClient = builder.healthWebClient(prisonApiBaseUri, healthTimeout) | ||
* | ||
* @Bean | ||
* fun prisonApiWebClient(authorizedClientManager: OAuth2AuthorizedClientManager, builder: WebClient.Builder): WebClient = | ||
* builder.authorisedWebClient(authorizedClientManager, registrationId = "prison-api", url = prisonApiBaseUri, timeout) | ||
* ``` | ||
*/ | ||
// @Bean | ||
fun authorizedClientManager( | ||
clientRegistrationRepository: ClientRegistrationRepository, | ||
oAuth2AuthorizedClientService: OAuth2AuthorizedClientService, | ||
): OAuth2AuthorizedClientManager { | ||
val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials().build() | ||
return AuthorizedClientServiceOAuth2AuthorizedClientManager( | ||
clientRegistrationRepository, | ||
oAuth2AuthorizedClientService, | ||
).kotlinApply { setAuthorizedClientProvider(authorizedClientProvider) } | ||
} | ||
} | ||
|
||
fun WebClient.Builder.authorisedWebClient(authorizedClientManager: OAuth2AuthorizedClientManager, registrationId: String, url: String, timeout: Duration): WebClient { | ||
val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager).kotlinApply { | ||
setDefaultClientRegistrationId(registrationId) | ||
} | ||
|
||
return baseUrl(url) | ||
.clientConnector(ReactorClientHttpConnector(HttpClient.create().responseTimeout(timeout))) | ||
.filter(oauth2Client) | ||
.build() | ||
} | ||
|
||
fun WebClient.Builder.healthWebClient(url: String, healthTimeout: Duration): WebClient = | ||
baseUrl(url) | ||
.clientConnector(ReactorClientHttpConnector(HttpClient.create().responseTimeout(healthTimeout))) | ||
.build() |
27 changes: 27 additions & 0 deletions
27
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppstemplatepackagename/health/HealthCheck.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package uk.gov.justice.digital.hmpps.hmppstemplatepackagename.health | ||
|
||
import org.springframework.beans.factory.annotation.Qualifier | ||
import org.springframework.boot.actuate.health.Health | ||
import org.springframework.boot.actuate.health.ReactiveHealthIndicator | ||
import org.springframework.stereotype.Component | ||
import org.springframework.web.reactive.function.client.WebClient | ||
import org.springframework.web.reactive.function.client.WebClientResponseException | ||
import reactor.core.publisher.Mono | ||
|
||
abstract class HealthCheck(private val webClient: WebClient) : ReactiveHealthIndicator { | ||
|
||
override fun health(): Mono<Health> = webClient.get() | ||
.uri("/health/ping") | ||
.retrieve() | ||
.toEntity(String::class.java) | ||
.flatMap { Mono.just(Health.up().withDetail("HttpStatus", it?.statusCode).build()) } | ||
.onErrorResume(WebClientResponseException::class.java) { | ||
Mono.just( | ||
Health.down(it).withDetail("body", it.responseBodyAsString).withDetail("HttpStatus", it.statusCode).build(), | ||
) | ||
} | ||
.onErrorResume(Exception::class.java) { Mono.just(Health.down(it).build()) } | ||
} | ||
|
||
@Component("hmppsAuthApi") | ||
class OAuthApiHealth(@Qualifier("oauthApiHealthWebClient") webClient: WebClient) : HealthCheck(webClient) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
60 changes: 60 additions & 0 deletions
60
...test/kotlin/uk/gov/justice/digital/hmpps/hmppstemplatepackagename/helper/JwtauthHelper.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
package uk.gov.justice.digital.hmpps.hmppstemplatepackagename.helper | ||
|
||
import io.jsonwebtoken.Jwts | ||
import org.springframework.context.annotation.Bean | ||
import org.springframework.context.annotation.Primary | ||
import org.springframework.http.HttpHeaders | ||
import org.springframework.security.oauth2.jwt.JwtDecoder | ||
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder | ||
import org.springframework.stereotype.Component | ||
import java.security.KeyPair | ||
import java.security.KeyPairGenerator | ||
import java.security.interfaces.RSAPublicKey | ||
import java.time.Duration | ||
import java.util.Date | ||
import java.util.UUID | ||
|
||
@Component | ||
class JwtAuthHelper { | ||
private val keyPair: KeyPair = KeyPairGenerator.getInstance("RSA").apply { initialize(2048) }.generateKeyPair() | ||
|
||
@Bean | ||
@Primary | ||
fun jwtDecoder(): JwtDecoder = NimbusJwtDecoder.withPublicKey(keyPair.public as RSAPublicKey).build() | ||
|
||
fun setAuthorisation( | ||
user: String = "AUTH_ADM", | ||
roles: List<String> = listOf(), | ||
scopes: List<String> = listOf(), | ||
): (HttpHeaders) -> Unit { | ||
val token = createJwt( | ||
subject = user, | ||
scope = scopes, | ||
expiryTime = Duration.ofHours(1L), | ||
roles = roles, | ||
) | ||
return { it.set(HttpHeaders.AUTHORIZATION, "Bearer $token") } | ||
} | ||
|
||
internal fun createJwt( | ||
subject: String?, | ||
scope: List<String>? = listOf(), | ||
roles: List<String>? = listOf(), | ||
expiryTime: Duration = Duration.ofHours(1), | ||
jwtId: String = UUID.randomUUID().toString(), | ||
): String = | ||
mutableMapOf<String, Any>() | ||
.also { subject?.let { subject -> it["user_name"] = subject } } | ||
.also { it["client_id"] = "test-app" } | ||
.also { roles?.let { roles -> it["authorities"] = roles } } | ||
.also { scope?.let { scope -> it["scope"] = scope } } | ||
.let { | ||
Jwts.builder() | ||
.id(jwtId) | ||
.subject(subject) | ||
.claims(it.toMap()) | ||
.expiration(Date(System.currentTimeMillis() + expiryTime.toMillis())) | ||
.signWith(keyPair.private, Jwts.SIG.RS256) | ||
.compact() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
50 changes: 50 additions & 0 deletions
50
.../uk/gov/justice/digital/hmpps/hmppstemplatepackagename/integration/TimeResourceIntTest.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package uk.gov.justice.digital.hmpps.hmppstemplatepackagename.integration | ||
|
||
import org.assertj.core.api.Assertions.assertThat | ||
import org.junit.jupiter.api.Test | ||
import java.time.LocalDate | ||
|
||
class TimeResourceIntTest : IntegrationTestBase() { | ||
|
||
@Test | ||
fun `should return unauthorized if no token`() { | ||
webTestClient.get() | ||
.uri("/time") | ||
.exchange() | ||
.expectStatus().isUnauthorized | ||
} | ||
|
||
@Test | ||
fun `should return forbidden if no role`() { | ||
webTestClient.get() | ||
.uri("/time") | ||
.headers(setAuthorisation(roles = listOf())) | ||
.exchange() | ||
.expectStatus().isForbidden | ||
.expectBody().jsonPath("status").isEqualTo(403) | ||
} | ||
|
||
@Test | ||
fun `should return forbidden if wrong role`() { | ||
webTestClient.get() | ||
.uri("/time") | ||
.headers(setAuthorisation(roles = listOf("ROLE_WRONG"))) | ||
.exchange() | ||
.expectStatus().isForbidden | ||
.expectBody().jsonPath("status").isEqualTo(403) | ||
} | ||
|
||
@Test | ||
fun `should return OK`() { | ||
webTestClient.get() | ||
.uri("/time") | ||
.headers(setAuthorisation(roles = listOf("ROLE_TEMPLATE_EXAMPLE"))) | ||
.exchange() | ||
.expectStatus() | ||
.isOk | ||
.expectBody() | ||
.jsonPath("$").value<String> { | ||
assertThat(it).startsWith("${LocalDate.now()}") | ||
} | ||
} | ||
} |
Oops, something went wrong.