Как решить: конечная точка принимает только запросы POST. Получен GET-запросAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Как решить: конечная точка принимает только запросы POST. Получен GET-запрос

Сообщение Anonymous »

Я попробовал реализовать вход в Microsoft в приложении Flutter с Firebase. После входа в систему я получаю следующую ошибку: Конечная точка принимает только запросы POST. Получен запрос GET., но пользователь неправильно перенаправлен в мое приложение. При повторном открытии приложения я успешно вошел в систему.
Я использовал код:
main.file

Код: Выделить всё

import 'package:aad_oauth/model/config.dart';
import 'package:firmparking/pages/General/InitialiseScreen.dart';
import 'package:firmparking/pages/General/RequestWaiting.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firmparking/pages/General/HomePage.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'classes/Admin.dart';
import 'classes/UserRequest.dart';
import 'general/functions.dart';
import 'general/functionsFirebaseRead.dart';
import 'general/functionsFirebaseWrite.dart';
import 'pages/General/Login.dart';
import 'package:platform/platform.dart';

//BUILD BEFEHLE:
//WEB: flutter build web
//IOS: flutter build ipa
//ANDROID: flutter clean & flutter build appbundle

void main() async {
final platform = LocalPlatform();

FirebaseOptions options = const FirebaseOptions(
apiKey: "xxx",
authDomain: "xxx.firebaseapp.com",
projectId: "xxx",
storageBucket: "xxx.appspot.com",
messagingSenderId: "175732871753",
appId: "xxx",
measurementId: "xxx",
);

WidgetsFlutterBinding.ensureInitialized();

if (kIsWeb || platform.isAndroid) {
await Firebase.initializeApp(options: options);
} else {
await Firebase.initializeApp();
}
//      allow read, write: if request.auth != null;
initializeDateFormatting();
//PushNotificationService().initNotifications();
//addLockFieldToParkingSpots();
//test
runApp(const FirmParking());
}

final navigatorKey = GlobalKey();

class FirmParking extends StatelessWidget {
static Config config = Config(
tenant: "common",
clientId: "xxx",
scope:
"https://graph.microsoft.com/User.Read https://graph.microsoft.com/Calendars.ReadWrite offline_access", //offline_access
redirectUri: "https://webapp.firmparking.de/",
navigatorKey: navigatorKey,
);

const FirmParking({super.key});

@override
Widget build(BuildContext context) {
Color canvasColor = Colors.white;
return MaterialApp(
title: "FirmParking",
debugShowCheckedModeBanner: false,
navigatorKey: navigatorKey,
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [
Locale('de'),
],
// Set the initial locale to German (Germany)
locale: const Locale('de'),
theme: ThemeData(
useMaterial3: false,
canvasColor: canvasColor,
dialogBackgroundColor: canvasColor,
cardTheme: const CardTheme(
surfaceTintColor: Colors.transparent,
),
dialogTheme: DialogTheme(
backgroundColor: canvasColor,
surfaceTintColor: Colors.transparent,
),
fontFamily: "Helvetica Neue",
),
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, authSnapshot) {
final user = authSnapshot.data;
if (user != null) {
if (authSnapshot.hasError) {
return Text('Error: ${authSnapshot.error}');
} else {
return FutureBuilder(
future: getAdmin(user.uid),
builder: (context, AsyncSnapshot  dataSnapshot) {
if (dataSnapshot.connectionState == ConnectionState.waiting) {
return returnLoadingWidget(Colors.white);
} else {
if (dataSnapshot.hasError) {
return const Text('Something went wrong main 0');
}
if (!dataSnapshot.hasData) {
//return const Text('Something went wrong kkkkkkk');
// USER IS NOT REGISTERED YET, CHECK IF COMPANY IS REGISTERED - IF SO OPEN WAITING SCREEN
// - IF NOT GIVE BACK ERROR MESSAGE
return FutureBuilder(
future: getAdmins(),
builder: (context,
AsyncSnapshot adminSnapshot) {
if (adminSnapshot.connectionState ==
ConnectionState.waiting) {
return returnLoadingWidget(Colors.white);
} else {
if (adminSnapshot.hasError) {
return const Text('Something went wrong main 1');
}
if (!adminSnapshot.hasData) {
return const Text('Something went wrong main 2');
}
List admins = adminSnapshot.data!;
bool companyExists = false;
String? adminID;
Admin? adminCache;
for (var admin in admins) {
if (admin.companies.contains(getDomainOfEmail(
user.email!.toLowerCase()))) {
companyExists = true;
adminID = admin.adminID;
adminCache = admin;
}
}
if (companyExists) {
Admin admin = admins.firstWhere(
(admin) => admin.adminID == adminID);
if (admin.acceptAzureUserAutomatically) {
return InitialiseScreen(
admin: adminCache!,
userID: user.uid,
needForCallAcceptAutomatically: true,
request: UserRequest(
email: user.email!,
userID: user.uid,
adminID: admin.adminID),
);
} else {
addUserRequest(
context, adminID!, user.uid, user.email!);
return RequestWaiting(
admin: adminCache!, userID: user.uid);
}
} else {
FirebaseAuth.instance.currentUser!.delete();
Fluttertoast.showToast(
msg: "Dein Unternehmen ist nicht registriert",
toastLength: Toast.LENGTH_SHORT,
timeInSecForIosWeb: 3,
textColor: Colors.white,
fontSize: 16.0);
return const Login();
}
}
},
);
} else {
navigatorKey.currentState!
.popUntil((route) =>  route.isFirst);
Admin admin = dataSnapshot.data!;
//migrateData();
return HomePage(admin: admin);
}
}
},
);
}
} else {
return const Login();
}
},
),
);
}
}

Логин.файл

Код: Выделить всё

import 'package:email_validator/email_validator.dart';
import 'package:firebase_auth/firebase_auth.dart' as fire;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../general/functions.dart';
import '../../general/functionsFirebaseWrite.dart';
import '../../main.dart';
import '../../theme/colors.dart';
//import 'dart:io' show Platform;

class Login extends StatefulWidget {
const Login({super.key});

@override
State createState() => LoginState();
}

class LoginState extends State {
late String? errorPassword = null;
late String? errorEmail = null;
late bool passwordVisible;
final emailController = TextEditingController();
final passwordController = TextEditingController();

@override
void dispose() {
emailController.dispose();
passwordController.dispose();
super.dispose();
}

@override
void initState() {
passwordVisible = false;
}

Future onLoginClicked() async {
setState(() {
errorEmail = null;
errorPassword = null;
});
showLoaderDialog(context);
try {
await fire.FirebaseAuth.instance.signInWithEmailAndPassword(
email: emailController.text.trim(),
password: passwordController.text.trim(),
); //LOGIC THAT HANDLES THE LOGIN IS IN THE STREAM BUILDER OF THE main.dart WIDGET TREE
navigatorKey.currentState!.popUntil((route) => route.isFirst);
} on fire.FirebaseAuthException catch (error) {
navigatorKey.currentState!.popUntil((route) => route.isFirst);
giveBackErrorMessage(error.message!);
}
}

Future onMicrosoftLoginClicked() async {
final microsoftProvider = fire.MicrosoftAuthProvider();
microsoftProvider.setCustomParameters({'prompt': 'select_account'});
microsoftProvider.addScope('User.Read'); // Request mandatory permission
showLoaderDialog(context);

try {
if (kIsWeb) {
// Web platform
final credential =
await fire.FirebaseAuth.instance.signInWithPopup(microsoftProvider);
Navigator.of(context, rootNavigator: true).pop();
return credential;
} else {
// Mobile platform
Navigator.of(context, rootNavigator: true).pop();
final credential = await fire.FirebaseAuth.instance
.signInWithProvider(microsoftProvider);
return credential;
}
} on fire.FirebaseAuthException catch (error) {
Navigator.of(context, rootNavigator: true).pop();
giveBackErrorMessage(error.message!);
return null;
} catch (error) {
Navigator.of(context, rootNavigator: true).pop();
giveBackErrorMessage('An unexpected error occurred: ${error.toString()}');
return null;
}
}

giveBackErrorMessage(String error) {
String errorMess;
if (error ==
"The password is invalid or the user does not have a password.") {
errorMess =
"Passwort ist falsch. Oder das Konto ist mit Microsoft verknüpft.";
setState(() {
errorPassword = errorMess;
});
} else if (error ==
"There is no user record corresponding to this identifier. "
"The user may have been deleted.") {
errorMess = "Email ist nicht bekannt.";
setState(() {
errorEmail = errorMess;
});
} else if (error ==
"Access to this account has been temporarily disabled due "
"to many failed login attempts. You can immediately restore it by resetting "
"your password or you can try again later.") {
//Utils.showSnackbar(error.message);
errorMess = "Account temporär gesperrt.  Später erneut versuchen";
setState(() {
errorEmail = errorMess;
});
} else if (error ==
"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.") {
errorMess =
"Diese Email ist mit einem FirmParking-Konto verknüpft. Bitte loggen sie sich hier ein.";
setState(() {
errorEmail = errorMess;
});
} else {
print(error);
errorMess = "Fehler beim anmelden. Erneut versuchen.";
setState(() {
errorEmail = errorMess;
});
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 60),
child: Wrap(
children: [
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: 150),
Image.asset(
'assets/logo_round.png', // Replace with your own image
width: 180,
),
const SizedBox(height: 80),
SizedBox(
width: 250,
child: TextFormField(
textAlign: TextAlign.center,
controller: emailController,
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (email) {
email != null && !EmailValidator.validate(email)
? "Email falsch formatiert"
: null;
return null;
},
decoration: InputDecoration(
labelText: 'Email',
errorText: errorEmail,
errorMaxLines: 3,
filled: true,
fillColor: Colors.grey[200],
labelStyle: const TextStyle(
color: CustomColor.darkBlueColor,
fontSize: 14,
fontWeight: FontWeight.normal,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide.none,
),
contentPadding: const EdgeInsets.symmetric(
vertical: 5,
horizontal: 20,
),
),
),
),
const SizedBox(height: 20),
SizedBox(
width: 250,
child: TextFormField(
textAlign: TextAlign.center,
controller: passwordController,
obscureText: !passwordVisible,
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (pwd) {
pwd != null && pwd.length < 6
? "Min.  6 Zeichen eingeben"
: null;
return null;
},
decoration: InputDecoration(
suffixIcon: IconButton(
icon: Icon(
passwordVisible
? Icons.visibility
: Icons.visibility_off,
color: CustomColor.blueColor,
size: 15,
),
onPressed: () {
setState(() {
passwordVisible = !passwordVisible;
});
},
),
labelStyle: const TextStyle(
color: CustomColor.darkBlueColor,
fontSize: 14,
fontWeight: FontWeight.normal,
),
errorText: errorPassword,
errorMaxLines: 2,
labelText: 'Passwort',
filled: true,
fillColor: Colors.grey[200],
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide.none,
),
contentPadding: const EdgeInsets.symmetric(
vertical: 5,
horizontal: 20,
),
),
),
),
const SizedBox(
height: 10,
),
Align(
alignment: Alignment.center,
child: GestureDetector(
onTap: () {
if (EmailValidator.validate(
emailController.text.trim())) {
onForgetPasswordClicked(
context, emailController.text.trim());
} else {
setState(() {
errorEmail = "Geben sie eine valide Email ein";
});
}
},
child: const Text(
'Passwort vergessen?',
style: TextStyle(
color: CustomColor.darkBlueColor,
fontWeight: FontWeight.normal,
),
),
),
),
const SizedBox(height: 40),
SizedBox(
width: 250,
child: ElevatedButton(
onPressed: () =>  onLoginClicked(),
style: ElevatedButton.styleFrom(
backgroundColor: CustomColor.darkBlueColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
padding: const EdgeInsets.symmetric(
vertical: 10,
horizontal: 40,
),
),
child: Container(
width: double.infinity,
alignment: Alignment.center,
child: const Text(
'LOGIN',
style: TextStyle(
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
),
),
const SizedBox(height: 40),
Visibility(
visible: true,
child: TextButton(
onPressed: () {
onMicrosoftLoginClicked();
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset(
'assets/microsoft.png', // Replace with Microsoft logo
width: 20,
height: 20,
),
const SizedBox(width: 10),
const Text(
'LOGIN MIT MICROSOFT',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
],
),
],
),
),
);
}
}

Я настроил свой проект в соответствии с этой документацией:
Аутентификация с помощью Microsoft на Android
В то время как IOS и WEB работает хорошо, я получаю следующую ошибку при входе в систему на устройстве Android. При возвращении в приложение я успешно вхожу в систему. Единственное решение этой проблемы, которое я нашел, — это отключение параметра Блокировать сторонние файлы cookie и данные сайта. Я не хочу, чтобы всем моим пользователям приходилось это делать. Каким будет это взаимодействие с пользователем?
При добавлении следующего кода в мой манифест:

Код: Выделить всё








Подробнее здесь: [url]https://stackoverflow.com/questions/79036743/how-to-solve-the-endpoint-only-accepts-post-requests-received-a-get-request[/url]
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»