Skip to content

Instantly share code, notes, and snippets.

@sproctor
Last active March 23, 2022 22:26
Show Gist options
  • Save sproctor/10c30da4921923df6897311ae7d63c66 to your computer and use it in GitHub Desktop.
Save sproctor/10c30da4921923df6897311ae7d63c66 to your computer and use it in GitHub Desktop.
class AuthenticationManager {
fun authenticateUser(
domain: String,
clientId: String,
redirectUri: String,
scope: String,
audience: String,
) {
val verifier = createVerifier()
val challenge = createChallenge(verifier)
val url = createLoginUrl(
domain = domain,
clientId = clientId,
redirectUri = redirectUri,
scope = scope,
challenge = challenge,
audience = audience,
)
Desktop.getDesktop().browse(URI(url))
}
private fun createLoginUrl(
domain: String,
clientId: String,
redirectUri: String,
scope: String,
challenge: String,
audience: String,
): String {
val encodedRedirectUri = URLEncoder.encode(redirectUri, Charsets.UTF_8)
val encodedScope = URLEncoder.encode(scope, Charsets.UTF_8)
return "https://$domain/authorize?response_type=code&code_challenge=$challenge" +
"&code_challenge_method=S256&client_id=$clientId&redirect_uri=$encodedRedirectUri" +
"&scope=$encodedScope&audience=$audience"
}
private fun createVerifier(): String {
val sr = SecureRandom()
val code = ByteArray(32)
sr.nextBytes(code)
return java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(code)
}
private fun createChallenge(verifier: String): String {
val bytes: ByteArray = verifier.toByteArray(Charsets.US_ASCII)
val md = MessageDigest.getInstance("SHA-256")
md.update(bytes, 0, bytes.size)
val digest = md.digest()
return Base64.encodeBase64URLSafeString(digest)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment