I have version of similar Firebase authentification and it’s work just fine. but the second (below) doesn’t work at all.
Tamplete “login” uses spring security whith login page configured to (.loginPage(“/login”)) so i think it’s because of spring security. i’ve tryed to delete first part of html template but it has no effect.
@GetMapping("/login")
public String showLoginPage(Model model) {
return "login"; // Возвращает имя представления login.html или login.jsp
}
@GetMapping("/get-token")
@ResponseBody
public String getToken1() {
try {
serviceAccount = new FileInputStream("./my-aws-6e0f8-firebase-adminsdk-q06q0-78540b7e56.json");
} catch (Exception e) {
System.out.println("no key");
}
try {
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();
} catch (Exception e) {
System.out.println("options error");
}
FirebaseApp.initializeApp(options);
try {
customToken = FirebaseAuth.getInstance().createCustomTokenAsync(UID).get();
} catch (Exception e) {
System.out.println("get token error");
}
System.out.println(customToken);
return customToken;
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
<div style="text-align: right;">
<a href="/">На главную страницу</a>
</div>
<script type="module" src="https://www.gstatic.com/firebasejs/10.3.0/firebase-app.js"></script>
<script type="module" src="https://www.gstatic.com/firebasejs/10.3.0/firebase-analytics.js"></script>
<script type="module" src="https://www.gstatic.com/firebasejs/10.3.0/firebase-auth.js"></script>
</head>
<body>
<h1>Login Page</h1>
<p th:if="${param.resetSuccess}">Your password has been reset successfully!</p>
<p th:if="${param.passwordReset}">Your password has been changed successfully!</p>
<!-- Остальной код страницы логина -->
<div style="text-align: right;">
<span th:if="${#httpServletRequest.userPrincipal != null}">
Пользователь: <span th:text="${#httpServletRequest.userPrincipal.name}"></span>
<form th:action="@{/logout}" method="post">
<input type="submit" value="Выйти"/>
</form>
</span>
</div>
<form th:action="@{/login}" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>
<br>
<a href="/register"><button>Register</button></a> <br> <br>
<a href="/forgot-password"><button>Забыли пароль?</button></a> <br> <br>
<!-- Сообщение об ошибке -->
<div th:if="${param.error}">
<p style="color: red;">Пользователь не найден</p>
</div>
<script type="module">
import { initializeApp } from 'https://www.gstatic.com/firebasejs/10.3.0/firebase-app.js';
import { getAnalytics } from 'https://www.gstatic.com/firebasejs/10.3.0/firebase-analytics.js';
import { getAuth, signInWithCustomToken} from 'https://www.gstatic.com/firebasejs/10.3.0/firebase-auth.js';
const firebaseConfig = {
apiKey: "AIzaSyCC7XORgSSdu4gq4OGZQ4G0XKAgy7K5STM",
authDomain: "my-aws-6e0f8.firebaseapp.com",
projectId: "my-aws-6e0f8",
storageBucket: "my-aws-6e0f8.appspot.com",
messagingSenderId: "567282066781",
appId: "1:567282066781:web:52a68db33898707420b4b4",
measurementId: "G-8VML47T1BF"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
// Получение токена с помощью Fetch API
fetch('/get-token')
.then(response => response.text())
.then(tokenFromServer => {
document.getElementById('token').textContent = tokenFromServer;
const auth = getAuth(app);
signInWithCustomToken(auth, tokenFromServer)
.then((userCredential) => {
// Пользователь успешно вошел
const user = userCredential.user;
// ...
})
.catch((error) => {
// Обработка ошибки при входе пользователя
const errorCode = error.code;
const errorMessage = error.message;
// ...
});
})
.catch(error => console.log(error));
</script>
</body>
</html>