google oauth return Неверный код проверки - PullRequest
0 голосов
/ 19 января 2020

Я пытаюсь войти в систему с Google OAUT. В веб-приложении я успешно захожу в систему с angular -oauth2-oid c:

login() {
    const authConfig: AuthConfig = {
        issuer: 'https://accounts.google.com',
        redirectUri: window.location.origin + '/user-authenticated',
        tokenEndpoint: 'https://www.googleapis.com/oauth2/v4/token',
        clientId: 'my cliet id here',
        strictDiscoveryDocumentValidation: false,
        responseType: 'code',
        scope: 'openid profile email',
        showDebugInformation: true,
    };

    this.oauthService.configure(authConfig);
    this.oauthService.tokenValidationHandler = new JwksValidationHandler();
    this.oauthService.loadDiscoveryDocumentAndTryLogin();

    this.oauthService.initLoginFlow(); 

После этого я получил ответ:

http://localhost:9000/user-authenticated?state=<STATE>&code=<CODE>&scope=...

Я отправляю этот код в свой оставшийся API , потому что я хотел бы обменять этот код на access_token и получить информацию о пользователе. Моя конечная точка:

@RestController
@RequestMapping("/api/sso")
class SSOAuthenticationEndpoint {

    private val logger = LoggerFactory.getLogger(this.javaClass)

    @Value("\${spring.security.oauth2.client.registration.google.clientId}")
    private lateinit var clientId: String

    @Value("\${spring.security.oauth2.client.registration.google.clientSecret}")
    private lateinit var clientSecret: String

    @PutMapping("oneTimeCode")
    fun authenticateWithOneTimeCode(@RequestBody oneTimeCode: String): String {
        val verifier: String = createVerifier()
        val challenge = createChallenge(verifier)

        val request = GoogleAuthorizationCodeTokenRequest(
            NetHttpTransport(),
            JacksonFactory.getDefaultInstance(),
            "https://www.googleapis.com/oauth2/v4/token",
            clientId,
            clientSecret,
            oneTimeCode,
            "http://localhost:9000/user-authenticated")

        request.set("code_verifier", verifier)
        request.set("code_challenge", challenge)
        request.set("code_challenge_method", "S256")
        request.set("grant_type", "authorization_code")
        request.execute()

        return "done"
    }

    private fun createChallenge(verifier: String): String {
        val bytes = verifier.toByteArray(charset("US-ASCII"))
        val md = MessageDigest.getInstance("SHA-256")
        md.update(bytes, 0, bytes.size)
        val digest = md.digest()
        return Base64.encodeBase64URLSafeString(digest)
    }

    private fun createVerifier(): String {
        val code = ByteArray(32)
        SecureRandom().nextBytes(code)
        return Base64.encodeBase64String(code)
    }
}

К сожалению, я получил исключение из request.execute ():

{
  "error": "invalid_grant",
  "error_description": "Invalid code verifier."
}

Понятия не имею, что не так: / Без переданного code_verifier у меня тоже самое исключение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...