Home > Enterprise >  display html pages to logged in users only
display html pages to logged in users only

Time:06-07

I've made a simple authentification using JS Fetch api , but the problem now is I don't know how can I secure my html pages ( I mean to not allow users who aren't logged in to view those pages). there are many tutorials on authentification and authorization but it's not what I'm looking for, most of them are working with Asp.net or react etc..

PS: for the frontend, I'm only using html/css/ js and for the backend , I'm using spring boot.

CodePudding user response:

Fatima. There are several ways in which you can do this. My recommendation, since you are using html/css and vanilla JS, is to call your auth endpoint, store in the session the necessary data (auth token, timeout, whatever you have), and create a route guard, which is a piece of JS that checks if the data stored in the session is valid, before allowing the page to be visualized. Note that this is not an optimized code, and that there are safer ways.

Auth:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Save your auth data to session
       localStorage.setItem("auth", xhr.response)
    }
};
xhttp.open("POST", "your/auth/endnpoint");
xhttp.send();

Route guard:

authData = localStorage.getItem("auth")
//Make your validations here.
if(authData){

}else{
    window.location.href = "your-permission-error-page";
}

If you import the route guard on every page you have, if your validation fails the user can be redirected to an error page.

  • Related