top of page
Writer's picturePushp Raj

SPA Authentication



Many web apps created using modern frameworks, such as React, Vue, and Angular, are single-page applications (SPAs) that manage routing and rendering client-side rather than obtaining each rendered page from the server. Atlas App Services may host and offer your SPA to clients.


To host your app, you must specify that it is a SPA in App Services. App Services processes requests for a particular resource by default by returning the file hosted at the supplied resource path or a 404 if no file matches the path. However, because SPAs render in a particular HTML file, all queries should return that file regardless of the requested resource URL.


This article will show you how to enable App Services Hosting to redirect all resource requests to a single file to support the SPA paradigm.


Note: 404 Errors with Single-Page Applications


App Services always sends an HTTP 200 response with the app root when single-page application hosting is enabled, regardless of the requested path. This means that a SPA cannot have a custom 404 page. You should instead put custom code in your application to handle invalid routes.


What exactly is authentication?


The process of showing that a fact or document is genuine is called authentication. This word is often linked with proving a user's identification in computer science. A user typically establishes their identity by giving credentials, agreed-upon information communicated between the user and the system.


Username and Password Authentication


The most common authentication system is the username and password combination, often known as password authentication.


A well-known example is accessing a user account on a website or service provider, such as Facebook or Gmail. Before accessing your account, you must first show that you have the necessary login credentials. Services often provide a screen that requests a username and password. The data entered by the user is then compared to values previously saved in an internal repository.


If you provide a legitimate combination of these credentials, the service provider will let you proceed and grant you access to your account.


While the username, such as an email address, can be made public, the password must be kept private. Passwords must be secured from cyber criminals due to their confidentiality. Even though usernames and passwords are commonly used on the internet, they are known for being a weak security method that hackers regularly attack.


The first method is to enforce password strength, a difficulty that hostile attackers cannot quickly guess. A complicated combination of lowercase and uppercase letters, numbers, and special characters produces a powerful password. Otherwise, a good character combination results in a stronger password.


End users are renowned for using weak passwords. SplashData, an internet security business, discovered the 25 most used passwords in their yearly study. According to the list based on millions of passwords disclosed through data breaches, millions of users rely on passwords such as "123456" and "password" to authenticate.


It comes down to usability, as weak passwords are usually easier to remember. Furthermore, people frequently use the same password for multiple websites or services.


Because weak passwords are easy to guess, the combination of these circumstances may result in security difficulties, and the leaked password can be used to access various services for the same user.


On the other hand, strong passwords used for authentication can withstand brute force attacks but are useless against phishing, keylogger software, or password stuffing. These attacks do not attempt to guess the user's password but rather steal it directly from the user.


Passwords are also a problem when they are not properly saved. In a recent news piece, for example, it was revealed that Facebook had kept millions of Instagram passwords in plain text. Passwords should be protected using best practices, such as hashing, at all times.


Passwordless Authentication/ Authentication without a password


Passwordless authentication, as the name implies, is an authentication system that does not require a password. The fundamental reason for this authentication is to reduce password fatigue, or the effort needed for the user to remember and keep a strong password secure.

By eliminating the need to memorize passwords, phishing attacks become obsolete.


You can do passwordless authentication with any authentication factor based on what you have and who you are. You can, for example, let the user use a service or application by delivering a code by email or facial recognition.


What is SPA Authentication?


The process of authenticating users in a Single Page Application (SPA) is referred to as SPA authentication. SPAs are web applications that load a single HTML page and dynamically update the content without reloading the full page. Because SPAs often rely on client-side rendering and communicate with back-end APIs, authentication in SPAs is unique.


Authentication in classic server-rendered web applications is frequently reliant on sessions and cookies. SPAs often use token-based authentication, such as JSON Web Tokens (JWTs), to authenticate users. Here's a high-level explanation of how JWT-based SPA authentication works:


  • When users log in to the SPA, their credentials (username/password) are transmitted to the server.

  • Server Validation: The server validates the credentials and generates a JWT if correct.

  • JWT Generation: The server generates a JWT with user-specific information (for example, user ID, roles, or permissions) and signs it with a secret key.

  • Token Storage: The JWT is received by the SPA and securely stored, typically in browser storage (e.g., local storage or session storage).

  • Token Usage: The SPA provides the JWT in the Authorization header or as a parameter in subsequent calls to protected resources or APIs.

  • Server verification occurs when the server receives the JWT, checks its integrity and signature with the secret key, and extracts the user information.

  • Access Control: The server evaluates if the user has the appropriate permissions to access the requested resource based on the retrieved information.

  • Response: Depending on the user's authorization status, the server responds to the SPA with the requested data or an error message.


Because user information is included within the token, SPA authentication allows the server to stay stateless by employing JWTs. This allows for scalability while also simplifying the development process. However, it necessitates careful management of security issues such as securely storing the secret key, guarding against token manipulation, and managing token expiration and renewal.


It is vital to note that the specific implementation of SPA authentication may differ based on the application's framework, libraries, and back-end technology stack.


Steps for App Services UI


Step 1: Submit Your Finished Application to App Services


Single-page apps are often rendered in a single HTML file called /index.html. The file should contain the JavaScript code required to wire up and cause your application, either inline in a script> element or imported from another file. You will also need to host any resources that will not be accessed via a CDN.


When you're ready to host your SPA, run the build script for your application and then upload the build folder to App Services.


Step 2: Setup App Services to Serve Your Application


After you've begun hosting your application files, you can immediately access your SPA by directly requesting the root HTML file. A request to any path other than the root file, on the other hand, will result in a 404. This can cause a SPA that utilizes a client-side router or otherwise relies on the URL path to behave unexpectedly.


  1. To tell App Services to serve the SPA's root page for all requests, do the following:

  2. In the App Services UI, go to the Hosting page and then choose the Settings tab.

  3. Make sure you have yet to supply a custom 404 page. If custom 404 is enabled, click the trash can icon () next to the 404 page you want to use.

  4. Choose the file next to Single Page Application. Click Select after selecting the base HTML file for your SPA.

  5. Save the file.


Steps for App Services CLI


Step 1: Get the Most Recent Version of Your App


A local copy of your application's configuration files is required to configure a single-page application using realm-cli.


Run the following commands to obtain a local copy of the most recent version of your app:

realm-cli pull --remote="<Your App ID>"


Note: You can also get a copy of your application's configuration files using the App Services UI's Deploy > Import/Export App screen.


Step 2: Add Your Developed Application Code


Single-page apps are often rendered in a single HTML file called /index.html. The file should contain the JavaScript code required to wire up and cause your application, either inline in a script> element or imported from another file. You will also need to host any resources that will not be accessed via a CDN.


When you're ready to host your SPA, run your application's build script and copy the result build folder into your application's /hosting/files directory.


Step 3: Setup App Services to Serve Your Application


Set default_response_code to 200 and default_error_path to the resource path of your SPA's

root HTML file in hosting/config.json. When you're finished, make sure to save the file.


{

"enabled": true,

"default_response_code": 200,

"default_error_path": "/index.html",

}


Step 4: Install the New Hosting Configuration.


After updating and saving hosting/config.json, you can push the revised configuration to your remote app. On push, Realm CLI immediately supports your SPA.


realm-cli push --remote="<Your App ID>" --include-hosting


Note: You must activate hosting in the App Services UI before you can use the Realm CLI with Static Hosting.

When access control is enabled on a MongoDB deployment, authentication is enforced, forcing users to identify themselves. Users can only perform activities defined by their roles when visiting a MongoDB deployment with access control enabled.


The following example uses the default authentication method to enable access control on a single MongoDB instance. A list of all supported authentication mechanisms may be found at Authentication Techniques.


User Administration


If access control is enabled, ensure that a user with the userAdmin or userAdminAnyDatabase roles exists in the admin database. This user can manage users and roles, including creating new users, assigning or removing functions from current users, and creating or changing custom roles.


MongoDB does not require a login or password to access or modify the database by default. It is necessary to enable and implement mandatory authentication.


To activate authentication, run the following commands:


Step 1: Launch a Mongo Shell.


mongo


Step 2: The database instar must have read and write access to the repository. Run the following commands in the MongoDB shell to create an administrator and a service user:

use admin


Step 3: Create an administrative user to manage database users:


db.createUser({user:'siteUserAdmin', pwd: '<secure password #1>',

roles:['userAdminAnyDatabase']})


Step 4: Log in as that account to validate the password:


db.auth('siteUserAdmin', '<secure password #1>')


Step 5: Make a user for the Repository service:


db.createUser({user:'spandan', pwd: '<secure password #2>',

roles:[{db:'binstar', role:'readWrite'}]})


Step 6: Enable needed authentication in MongoDB:


  • If you use the traditional MongoDB configuration style, add the auth key to /etc/mongod.conf:

auth=true

  • If you're using the current MongoDB configuration format, add the security.authorization key to /etc/mongod.conf:

security:

authorization: enabled


Step 7: Restart MongoDB to reload the settings:


sudo service mongod restart


Step 8: Change the MONGO URL option to mongodb:/username:password@hostname> in the Repository configuration file.


Step 9: After making changes to the configuration file, restart the repository to see the changes take effect.


Localhost is an Exception


Users can be added before or after access control is enabled. If you allow access control before creating users, MongoDB will support a local host exception. This allows you to add a user administrator to the admin database. After creating a user, you must log in as the administrator to add other users as needed.


Conclusion


Finally, SPA authentication is critical in protecting Single Page Applications (SPAs) by guaranteeing that only authorized users can access protected content and APIs. SPAs can easily authenticate users without relying on traditional session-based techniques by adopting token-based authentication, such as JSON Web Tokens (JWTs).


The usage of JWTs in SPA authentication has various benefits. It enables scalability by allowing the server to remain stateless. JWTs also allow for the secure transport of user-specific information within the token, removing the need to query the server for user data with each request. This improves performance while decreasing server load.


However, SPA authentication poses certain difficulties. JWTs must be securely stored on the client side to prevent unauthorized access and token theft. To balance security and user experience, token expiration and renewal processes must be carefully considered.


Furthermore, safeguarding against token manipulation and providing secure communication channels are critical for maintaining the authentication process's integrity and confidentiality.


Overall, SPA authentication with JWTs is a versatile and effective method of securing user authentication in SPAs. To construct secure authentication systems that safeguard user data and maintain the overall integrity of their apps, developers should be conversant with the best practices and security issues connected with JWT implementation.



Interesting FAQs



According to Rajeev Chandrasekhar, Minister of State for Electronics and Information and Technology, India will have 13.91 lakh cyber security incidents by 2022.

Because these figures only include information reported to and tracked by the Indian Computer Emergency Response Team (CERT-In), they do not provide an accurate picture of cyberattacks on the country.


However, reported cyberattacks declined in 2022 from 14.02 lakhs in 2021. According to government statistics, 2.08 million events were reported in 2018, 3.94 million attacks occurred in 2018, and 11.58 million cybersecurity incidents were reported to CERT-In in 2020.


What percentage of cyber-attacks has increased in 2022?


According to Check Point Research, new research on cyberattack patterns shows a 38% increase in global attacks in 2022 compared to 2021. The increase in cyberattacks is attributed to more agile hackers and ransomware gangs that focused on exploiting collaboration tools used by remote workers and schools and educational institutions that shifted to e-learning during the pandemic, as well as a significant increase in attacks on healthcare organizations.


Stay tuned to CipherSchools for more interesting tech articles.

4 views

Related Posts

See All

Comments


Subscribe to Our Newsletter

Thanks for submitting!

bottom of page