Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore/PRSD-NONE: mock one login endpoint #9

Merged
merged 9 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,13 @@ Database migrations <will be/ are> run at deployment time for all non-local depl
the `flywayMigrate` Gradle task. When developing locally using the `local` profile the migrations will run at
application start up. If you are using the `local` launch profile in IntelliJ, this will also run the `flywayClean` task
before running the migrations. After the migrations have run Spring Boot will then run the SQL in `data-local.sql` to
populate the database with seed data.
populate the database with seed data.

### Mock One Login Oauth2

For development, we've mocked elements of the governments one login system (that the web app will be using in deployment).
When you start the app using the `local` profile this will be available, when you attempt to login, This will automatically log you in as a user that has every role - and therefore can access all pages.

If you are adding new roles please add the user with the `userId` set in `MockOneLoginHelper` to that new role/table.

If you need to be able to login as a user that has specific roles then you can change the `userId` in `MockOneLoginHelper` to the id from the `one_login_user` table of a user that has the permissions you want.
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,15 @@ class CustomSecurityConfig {
.permitAll()
.requestMatchers("/register-as-a-landlord")
.permitAll()
.requestMatchers("/one-login-local/**")
.permitAll()
.anyRequest()
.authenticated()
}.oauth2Login(Customizer.withDefaults())
.csrf { requests ->
requests.ignoringRequestMatchers("/one-login-local/**")
}

return http.build()
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package uk.gov.communities.prsdb.webapp.local.api.mockOneLogin

import org.springframework.context.annotation.Profile
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.net.URI

@Profile("local")
@RestController
@RequestMapping("/one-login-local")
class MockOneLoginController(
private var helper: MockOneLoginHelper = MockOneLoginHelper(),
) {
@GetMapping("/.well-known/openid-configuration")
fun openidConfiguration(): String = helper.getOpenidConfigurationResponse()

@GetMapping("/.well-known/jwks.json")
fun jwksJson(): String = helper.getJwksJsonResponse()

@GetMapping("/authorize")
fun authorize(
@RequestParam response_type: String,
@RequestParam client_id: String,
@RequestParam scope: String,
@RequestParam state: String,
@RequestParam redirect_uri: String,
@RequestParam nonce: String,
): ResponseEntity<Unit> {
helper.lastReceivedNonce = nonce
val locationURI: URI = URI.create("$redirect_uri?code=${helper.authorizationCode}&state=$state")

return ResponseEntity.status(302).location(locationURI).build()
}

@PostMapping("/token")
fun token(
@RequestParam grant_type: String,
@RequestParam redirect_uri: String,
@RequestParam client_assertion: String,
@RequestParam client_assertion_type: String,
@RequestParam code: String,
): ResponseEntity<String> {
val responseBody = helper.getTokenResponse()

val responseBuild = ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(responseBody)

return responseBuild
}

@GetMapping("/userinfo")
fun userInfo(): ResponseEntity<String> {
val responseBody = helper.getUserInfoResponse()

val responseBuild = ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(responseBody)

return responseBuild
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
package uk.gov.communities.prsdb.webapp.local.api.mockOneLogin

import com.nimbusds.jose.Algorithm
import com.nimbusds.jose.JOSEObjectType
import com.nimbusds.jose.JWSAlgorithm
import com.nimbusds.jose.JWSHeader
import com.nimbusds.jose.crypto.ECDSASigner
import com.nimbusds.jose.jwk.Curve
import com.nimbusds.jose.jwk.ECKey
import com.nimbusds.jose.jwk.KeyUse
import com.nimbusds.jose.jwk.gen.ECKeyGenerator
import com.nimbusds.jwt.JWTClaimsSet
import com.nimbusds.jwt.SignedJWT
import java.time.Instant
import java.util.Date

class MockOneLoginHelper {
companion object {
val ecKey = generateSecretKey()

private fun generateSecretKey(): ECKey {
val ecKey =
ECKeyGenerator(Curve.P_256)
.keyUse(KeyUse.SIGNATURE)
.keyID("6a4bc1e3-9530-4d5b-90c5-10dcf3ffccd0")
.algorithm(Algorithm("ES256"))
.generate()

return ecKey
}
}

private val userId = "urn:fdc:gov.uk:2022:PQRST"
private val userEmail = "[email protected]"
private val userNumber = "07123456789"

val authorizationCode = "SplxlOBeZQQYbYS6WxSbIA"

var lastReceivedNonce: String? = null

private fun getIdToken(): String {
val headerBuilder: JWSHeader.Builder =
JWSHeader
.Builder(JWSAlgorithm.ES256)
.type(JOSEObjectType.JWT)
.jwk(ecKey.toPublicJWK())

val claimSetBBuilder: JWTClaimsSet.Builder =
JWTClaimsSet
.Builder()
.subject(userId)
.audience("l0AE7SbEHrEa8QeQCGdml9KQ4bk")
.issuer("http://localhost:8080/one-login-local/")
.issueTime(Date())
.expirationTime(Date.from(Instant.now().plusSeconds(300)))
.claim("vot", "Cl.Cm")
.claim("nonce", lastReceivedNonce)
.claim("vtm", "http://localhost:8080/one-login-local/trustmark")
.claim("sid", "Nzk0M2NiNWUtYWZhNC00ZjZmLThiOTItNzUxNjcyNjUwOGNl")

val signedJwt = SignedJWT(headerBuilder.build(), claimSetBBuilder.build())

signedJwt.sign(ECDSASigner(ecKey))

return signedJwt.serialize()
}

fun getOpenidConfigurationResponse(): String =
"{\n" +
"\"authorization_endpoint\": \"http://localhost:8080/one-login-local/authorize\",\n" +
"\"token_endpoint\": \"http://localhost:8080/one-login-local/token\",\n" +
"\"registration_endpoint\": \"http://localhost:8080/one-login-local/connect/register\",\n" +
"\"issuer\": \"http://localhost:8080/one-login-local/\",\n" +
"\"jwks_uri\": \"http://localhost:8080/one-login-local/.well-known/jwks.json\",\n" +
"\"scopes_supported\": [\n" +
"\"openid\",\n" +
"\"email\",\n" +
"\"phone\",\n" +
"\"offline_access\"\n" +
"],\n" +
"\"response_types_supported\": [\n" +
"\"code\"\n" +
"],\n" +
"\"grant_types_supported\": [\n" +
"\"authorization_code\"\n" +
"],\n" +
"\"token_endpoint_auth_methods_supported\": [\n" +
"\"private_key_jwt\",\n" +
"\"client_secret_post\"\n" +
"],\n" +
"\"token_endpoint_auth_signing_alg_values_supported\": [\n" +
"\"RS256\",\n" +
"\"RS384\",\n" +
"\"RS512\",\n" +
"\"PS256\",\n" +
"\"PS384\",\n" +
"\"PS512\"\n" +
"],\n" +
"\"ui_locales_supported\": [\n" +
"\"en\",\n" +
"\"cy\"\n" +
"],\n" +
"\"service_documentation\": \"https://docs.sign-in.service.gov.uk/\",\n" +
"\"op_policy_uri\": \"https://signin.integration.account.gov.uk/privacy-notice\",\n" +
"\"op_tos_uri\": \"https://signin.integration.account.gov.uk/terms-and-conditions\",\n" +
"\"request_parameter_supported\": true,\n" +
"\"trustmarks\": \"http://localhost:8080/one-login-local/trustmark\",\n" +
"\"subject_types_supported\": [\n" +
"\"public\",\n" +
"\"pairwise\"\n" +
"],\n" +
"\"userinfo_endpoint\": \"http://localhost:8080/one-login-local/userinfo\",\n" +
"\"end_session_endpoint\": \"http://localhost:8080/one-login-local/logout\",\n" +
"\"id_token_signing_alg_values_supported\": [\n" +
"\"ES256\",\n" +
"\"RS256\"\n" +
"],\n" +
"\"claim_types_supported\": [\n" +
"\"normal\"\n" +
"],\n" +
"\"claims_supported\": [\n" +
"\"sub\",\n" +
"\"email\",\n" +
"\"email_verified\",\n" +
"\"phone_number\",\n" +
"\"phone_number_verified\",\n" +
"\"wallet_subject_id\",\n" +
"\"https://vocab.account.gov.uk/v1/passport\",\n" +
"\"https://vocab.account.gov.uk/v1/socialSecurityRecord\",\n" +
"\"https://vocab.account.gov.uk/v1/drivingPermit\",\n" +
"\"https://vocab.account.gov.uk/v1/coreIdentityJWT\",\n" +
"\"https://vocab.account.gov.uk/v1/address\",\n" +
"\"https://vocab.account.gov.uk/v1/inheritedIdentityJWT\",\n" +
"\"https://vocab.account.gov.uk/v1/returnCode\"\n" +
"],\n" +
"\"request_uri_parameter_supported\": false,\n" +
"\"backchannel_logout_supported\": true,\n" +
"\"backchannel_logout_session_supported\": false\n" +
"}\n"

fun getJwksJsonResponse(): String =
"{\n" +
"\"keys\": [\n" +
"{\n" +
"\"kty\": \"EC\",\n" +
"\"use\": \"sig\",\n" +
"\"crv\": \"P-256\",\n" +
"\"kid\": \"6a4bc1e3-9530-4d5b-90c5-10dcf3ffccd0\",\n" +
"\"x\": \"${ecKey.toPublicJWK().x}\",\n" +
"\"y\": \"${ecKey.toPublicJWK().y}\",\n" +
"\"alg\": \"ES256\"\n" +
"},\n" +
"{\n" +
"\"kty\": \"EC\",\n" +
"\"use\": \"sig\",\n" +
"\"crv\": \"P-256\",\n" +
"\"kid\": \"644af598b780f54106ca0f3c017341bc230c4f8373f35f32e18e3e40cc7acff6\",\n" +
"\"x\": \"5URVCgH4HQgkg37kiipfOGjyVft0R5CdjFJahRoJjEw\",\n" +
"\"y\": \"QzrvsnDy3oY1yuz55voaAq9B1M5tfhgW3FBjh_n_F0U\",\n" +
"\"alg\": \"ES256\"\n" +
"},\n" +
"{\n" +
"\"kty\": \"EC\",\n" +
"\"use\": \"sig\",\n" +
"\"crv\": \"P-256\",\n" +
"\"kid\": \"e1f5699d068448882e7866b49d24431b2f21bf1a8f3c2b2dde8f4066f0506f1b\",\n" +
"\"x\": \"BJnIZvnzJ9D_YRu5YL8a3CXjBaa5AxlX1xSeWDLAn9k\",\n" +
"\"y\": \"x4FU3lRtkeDukSWVJmDuw2nHVFVIZ8_69n4bJ6ik4bQ\",\n" +
"\"alg\": \"ES256\"\n" +
"}\n" +
"]\n" +
"}"

fun getTokenResponse(): String {
val idToken: String = getIdToken()

val responseBody =
"{\n" +
"\"access_token\": \"SlAV32hkKG\",\n" +
"\"token_type\": \"Bearer\",\n" +
"\"expires_in\": 180,\n" +
"\"id_token\": \"$idToken\"\n" +
"}"

return responseBody
}

fun getUserInfoResponse(): String =
"{\n" +
" \"sub\": \"$userId\",\n" +
" \"email\": \"$userEmail\",\n" +
" \"email_verified\": true,\n" +
" \"phone_number\": \"$userNumber\",\n" +
" \"phone_number_verified\": true\n" +
"}"
}
7 changes: 6 additions & 1 deletion src/main/resources/application-local.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,14 @@ spring:
client-authentication-method: private_key_jwt
authorization-grant-type: authorization_code
scope: openid
redirect-uri: http://localhost:8080/login/oauth2/code/one-login
provider:
one-login:
issuer-uri: https://oidc.integration.account.gov.uk/
authorization-uri: http://localhost:8080/one-login-local/authorize
token-uri: http://localhost:8080/one-login-local/token
jwk-set-uri: http://localhost:8080/one-login-local/.well-known/jwks.json
user-info-uri: http://localhost:8080//one-login-local/userinfo
userNameAttribute: "sub"

one-login:
jwt:
Expand Down
24 changes: 16 additions & 8 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,22 @@ spring:
port: ${ELASTICACHE_PORT}
password: ${ELASTICACHE_PASSWORD}

one-login:
jwt:
public.key: ${ONE_LOGIN_PUBLIC_KEY}
private.key: ${ONE_LOGIN_PRIVATE_KEY}

server:
error:
path: /error

---

spring:
config:
activate:
on-profile: default

security:
oauth2:
client:
Expand All @@ -36,11 +52,3 @@ spring:
one-login:
issuer-uri: ${ONE_LOGIN_ISSUER_URL}

one-login:
jwt:
public.key: ${ONE_LOGIN_PUBLIC_KEY}
private.key: ${ONE_LOGIN_PRIVATE_KEY}

server:
error:
path: /error
9 changes: 6 additions & 3 deletions src/main/resources/data-local.sql
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
INSERT INTO one_login_user (id, name, email, created_date, last_modified_date)
VALUES ('urn:fdc:gov.uk:2022:ABCDE', 'Bob T Builder', '[email protected]', '09/13/24', '09/13/24'),
('urn:fdc:gov.uk:2022:FGHIJ', 'Anne Other', '[email protected]', '09/13/24', '09/13/24'),
('urn:fdc:gov.uk:2022:KLMNO', 'Ford Prefect', '[email protected]', '10/07/24', '10/07/24');
('urn:fdc:gov.uk:2022:KLMNO', 'Ford Prefect', '[email protected]', '10/07/24', '10/07/24'),
('urn:fdc:gov.uk:2022:PQRST', 'Julia Jones', '[email protected]', '10/14/24', '10/14/24');

INSERT INTO landlord_user (subject_identifier, phone_number, date_of_birth, created_date, last_modified_date)
VALUES ('urn:fdc:gov.uk:2022:ABCDE', '07712345678', '01/01/00', '09/13/24', '09/13/24'),
('urn:fdc:gov.uk:2022:FGHIJ', '07811111111', '11/23/98', '09/13/24', '09/13/24');
('urn:fdc:gov.uk:2022:FGHIJ', '07811111111', '11/23/98', '09/13/24', '09/13/24'),
('urn:fdc:gov.uk:2022:PQRST', '07123456789', '06/16/84', '10/14/24', '10/14/24');

INSERT INTO local_authority (name, created_date, last_modified_date)
VALUES ('Betelgeuse','09/13/24', '09/13/24');

INSERT INTO local_authority_user (subject_identifier, is_manager, local_authority_id, created_date, last_modified_date)
VALUES ('urn:fdc:gov.uk:2022:KLMNO',true, 1,'10/07/24', '10/07/24')
VALUES ('urn:fdc:gov.uk:2022:KLMNO',true, 1,'10/07/24', '10/07/24'),
('urn:fdc:gov.uk:2022:PQRST', true, 1, '10/14/24', '10/14/24');