Friday, April 17, 2020

Firebase Authentication for Web - Sign-in Method Email/Password Implementation

First go to https://firebase.google.com/docs/web/setup and create a project step by step by following https://console.firebase.google.com/.

Step 2: Register your app with Firebase

Go to https://console.firebase.google.com/u/0/project/test-firebase-auth-1/authentication/providers for enable signin method.

I enabled Email/Password authentication type for this example.

To initialize Firebase in your app, you need to provide your app's Firebase project configuration.

Go to Project Settings page for configure app and get API Key.



Step 3: Add Firebase SDKs and initialize Firebase, we will use CDN to load all necessary resources

<script src="//www.gstatic.com/firebasejs/7.14.0/firebase-app.js"></script>
<script src="//www.gstatic.com/firebasejs/7.8.1/firebase-auth.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        // Your web app's Firebase configuration
        var firebaseConfig = {
            apiKey: "AIzaSyA9XqTsdfsdfsdf0w9TSlYSlUlpCLcNjeM",
            authDomain: "test-firebase-auth-1.firebaseapp.com",
            databaseURL: "https://test-firebase-auth-1.firebaseio.com",
            projectId: "test-firebase-auth-1",
            storageBucket: "test-firebase-auth-1.appspot.com",
            messagingSenderId: "514502059460",
            appId: "1:51450324232059460:web:70b12cd2342345ee4287f932f091"
        };
        // Initialize Firebase
        var defaultProject = firebase.initializeApp(firebaseConfig);

        console.log(defaultProject.auth());
    });
</script>
You can restrict your API Key to specific domain using below steps:

1. Visit https://console.developers.google.com/apis
2. Go to your firebase project
3. Go to Credentials
4. Under API keys, select the Browser key associated with your firebase project (should have the same key as the API key you use to initialize your firebase app.)
5. Under "Accept requests from these HTTP referrers (web sites), simply add the URL of your app.



We are done from configure Firebase.

Now we will build our registration/login page.

Request Sample When User State Changed (Login,Logout,Registration)


defaultProject.auth().onAuthStateChanged(function(user) {
    if (user) {
        console.log("Logged in user details");
        console.log(user);

        console.log(user.displayName);
        console.log(user.email);
    }
    else {
        window.location.href = "/";
    }
});

Request Sample to Register User With Email/Password


defaultProject.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
    console.log(error);
    if (error.message) {
        alert(error.message);
    }
});

Request Sample to Login Action


defaultProject.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
    console.log(error);
    if (error.message) {
        alert(error.message);
    }
});

Password Reset Email Send Request

defaultProject.auth().sendPasswordResetEmail(email).then(function() {
    alert('Password Reset Email Sent!');
}).catch(function(error) {
    console.log(error);
    if (error.message) {
        alert(error.message);
    }
});

You can configure password reset URL



You can reset your password using below code snippet

const queryString = window.location.search;

const urlParams = new URLSearchParams(queryString);

const code = urlParams.get('oobCode');

defaultProject.auth().confirmPasswordReset(code, "Password-123456").then(function() {
    alert('Password Reset Completed');
}).catch(function(error) {
    console.log(error);
    if (error.message) {
        alert(error.message);
    }
});
Finally GibHUB link to the sample project


1 comment:

  1. Very enthralling blog
    Thanks for sharing the code sample. You did a wonderful job, Keep sharing this type of code sample. And yes, Web Hosting plays a very important role in the business world. And it is important to have the best hosting services. Buy the best USA VPS Hosting ​service for your website.

    ReplyDelete