Blazor WebAssembly & Firebase Authentication
1. Firebase account
2. Auth Providers should be enabled in firebase console
3. A little knowledge of JSIterop
4. A little knowledge of Javascript along with your existing C# skills
Step 1:
Create a project in Firebase console
Step 2:
Go to firebase console -> Setting icon -> General tab -> scroll down to 'your apps' and find 'sdk snippets'. Now click on 'Config' radio button and copy your firebaseConfig. It looks like this:
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
Step 3:
In your blazor webAssemby project, go to wwroot and create a js file called firebase.js. Paste the following code. Not here I am caching firebase auth tokens. You don't need to:
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
console.log("firebase.js loaded");;
window.FirebaseLogin = (instance) => {
var provider = new firebase.auth.GoogleAuthProvider();
if (localStorage.token){
instance.invokeMethod('LoginCallback', localStorage.email, localStorage.display, localStorage.token);
}
else {
firebase.auth().signInWithPopup(provider).then(function (result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
console.log(user);
localStorage.display = user.displayName;
localStorage.email = user.email;
localStorage.token = token;
instance.invokeMethod('LoginCallback', user.email, user.displayName, token);
}).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
}
};
window.FirebaseLogout = (instance) => {
firebase.auth().signOut().then(() => {
localStorage.display = "";
localStorage.email = "";
localStorage.token = "";
instance.invokeMethod('LogoutCallback');
});
};
Step 4:
Again go to firebase console -> Setting icon -> General tab -> scroll down to 'your apps' and find 'sdk snippets'. Now click on 'CDN' radio button and copy scripts references. You will need to paste them in your index.tml file right before the </body> tag.
Step 5:
Now create a razor component where you need login and logout functionality and paste these buttons:
<botton class="btn btn-info" @onclick="@(()=>Login())">Login</botton>
<botton class="btn btn-light" @onclick="@(()=>Logout())">Logout</botton>
Now paste the following code in your code behind file or @code{} area:
public static string User { get; set; } = "Not Signed In";
public static string Email { get; set; } = "Not Signed In";
public static string Token { get; set; } = "--";
[Inject]
public IJSRuntime JSRuntime { get; set; }
[JSInvokable]
public void LoginCallback(string email, string display, string token)
{
User = display;
Email = email;
Token = token;
InvokeAsync(StateHasChanged);
}
[JSInvokable]
public void LogoutCallback()
{
Console.WriteLine("Callback in C# called");
User = "Not Signed In";
Email = "Not Signed In";
InvokeAsync(StateHasChanged);
}
protected async Task Login()
{
await JSRuntime.InvokeAsync<object>("FirebaseLogin", DotNetObjectReference.Create(this));
}
protected async Task Logout()
{
await JSRuntime.InvokeAsync<object>("FirebaseLogout", DotNetObjectReference.Create(this));
}
That's it - Authenticate and enjoy!
Comments
Post a Comment