let nonce = String().randomNonceString()
currentNonce = nonce
let appleIDProvider = ASAuthorizationAppleIDProvider()
let request = appleIDProvider.createRequest()
request.requestedScopes = [.fullName, .email]
request.nonce = String().sha256(nonce)
let authorizationController = ASAuthorizationController(authorizationRequests: [request])
authorizationController.delegate = self
authorizationController.presentationContextProvider = self
authorizationController.performRequests()
}
func authorizationController(controller: ASAuthorizationController,
didCompleteWithAuthorization authorization: ASAuthorization) {
signupViewModel.appleLogin(authorization: authorization, currentNonce: currentNonce) {
self.loginDidSucceed {
UIApplication.shared.windows.first?.isUserInteractionEnabled = true
self.signupViewModel.searchUID()
}
}
}
func appleLogin(authorization: ASAuthorization,
currentNonce: String?, completion: @escaping() -> Void){
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
guard let nonce = currentNonce else {
fatalError("Invalid state: A login callback was received, but no login request was sent.")
}
guard let appleIDToken = appleIDCredential.identityToken else {
print("Unable to fetch identity token")
return
}
guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
return
}
if let authorizationCode = appleIDCredential.authorizationCode,
let codeString = String(data: authorizationCode, encoding: .utf8) {
print(codeString)
let url = URL(string: "https://MY-URL?code=\(codeString)".addi ... ntEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "https://apple.com")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
if let data = data {
let refreshToken = String(data: data, encoding: .utf8) ?? ""
print(refreshToken)
UserDefaults.standard.set(refreshToken, forKey: "refreshToken")
UserDefaults.standard.synchronize()
}
}
task.resume()
}
// Initialize a Firebase credential, including the user's full name.
let credential = OAuthProvider.credential(withProviderID: "apple.com",
idToken: idTokenString,
rawNonce: nonce)
// Sign in with Firebase.
Auth.auth().signIn(with: credential) { authResult, error in
if let error = error {
print("Error Apple sign in: \(error.localizedDescription)")
return
}
completion()
}
}
}
Приведенный выше код — это код входа в Apple. В MY-URL я использую URL-адрес, сохраненный в функциях Firebase. Однако при попытке выдать токен обновления с помощью этого кода возникает внутренняя ошибка сервера
. Глядя на журналы Firebase, это выглядит так:
AxiosError: Request failed with status code 400
at settle (/workspace/node_modules/axios/dist/node/axios.cjs
at IncomingMessage.handleStreamEnd (/workspace/node_modules/axios/dist/node/axios.cjs
at IncomingMessage.emit (node:events:529:35)
at IncomingMessage.emit (node:domain:552:15)
at endReadableNT (node:internal/streams/readable
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
at Axios.request (/workspace/node_modules/axios/dist/node/axios.cjs
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"
Я не знаю, что мне нужно сделать, чтобы решить эту проблему
Я пытался повторно загрузить функции Firebase и исправить index.js
я прикрепил свой код index.js
const functions = require("firebase-functions");
// The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
const {logger} = require("firebase-functions");
const {onRequest} = require("firebase-functions/v2/https");
const {onDocumentCreated} = require("firebase-functions/v2/firestore");
// The Firebase Admin SDK to access Firestore.
const {initializeApp} = require("firebase-admin/app");
const {getFirestore} = require("firebase-admin/firestore");
initializeApp();
function makeJWT() {
const jwt = require('jsonwebtoken')
const fs = require('fs')
// Path to download key file from developer.apple.com/account/resources/authkeys/list
let privateKey = fs.readFileSync('AuthKey_MyKeyID.p8');
//Sign with your team ID and key ID information.
let token = jwt.sign({
iss: 'YQC68LN7U3',
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 120,
aud: 'https://appleid.apple.com',
sub: 'com.yongheon.Healf-healthFreinds'
}, privateKey, {
algorithm: 'ES256',
header: {
alg: 'ES256',
kid: 'MyKeyID',
} });
return token;
}
exports.getRefreshToken = functions.https.onRequest(async (request, response) => {
//import the module to use
const axios = require('axios');
const qs = require('qs')
const code = request.query.code;
const client_secret = makeJWT();
let data = {
'code': code,
'client_id': 'com.yongheon.Healf-healthFreinds',
'client_secret': client_secret,
'grant_type': 'authorization_code'
}
return axios.post('https://appleid.apple.com/auth/token', qs.stringify(data), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
})
.then(async res => {
const refresh_token = res.data.refresh_token;
response.send(refresh_token);
});
});
exports.revokeToken = functions.https.onRequest( async (request, response) => {
//import the module to use
const axios = require('axios');
const qs = require('qs');
const refresh_token = request.query.refresh_token;
const client_secret = makeJWT();
let data = {
'token': refresh_token,
'client_id': 'com.yongheon.Healf-healthFreinds',
'client_secret': client_secret,
'token_type_hint': 'refresh_token'
};
return axios.post('https://appleid.apple.com/auth/revoke', qs.stringify(data), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
})
.then(async res => {
console.log(res.data);
response.send('Complete');
});
});
Подробнее здесь: https://stackoverflow.com/questions/784 ... h-firebase
Мобильная версия