Securing user access in Angular: managing new tab or new browser window

When developing my AngularJS-based application, I initially utilized localStorage to save the JWT authentication token obtained from the backend. The app employed an interceptor to send this token along with every request made to the backend server. This process functioned effectively until I encountered some challenges:

  1. An issue arose when my manager expressed concerns about utilizing localStorage to store the username and JWT auth token since they persist in the browser even if the user does not log out intentionally. Closing the browser without logging out leaves the cache stored in localStorage.

  2. To address the first problem, I switched to using sessionStorage to store the username and JWT auth token. However, this created further complications when users opened the app in a new tab or window by right-clicking certain links. In these instances, authentication failed because the app could not locate the JWT auth token in sessionStorage.

  3. Storing the username and JWT auth token as variables in the JavaScript code posed another issue: the data would be lost if the user refreshed the browser.

These difficulties surrounding the use of JWT authentication tokens in Angular have led me to seek better solutions. Is there a way to meet the requirement of avoiding localStorage usage while also enabling the app to maintain the same authentication JWT token across multiple tabs or windows? Thank you for any insights provided!

Answer №1

Your angular/server configuration seems to have a flaw that goes beyond just a token issue.

Typically, when a user opens a link in a new tab/window, it initiates a fresh session. The URL usually leads to a page requiring authentication, and in a new session, the angular app should work towards restoring it. If the user has logged in with the "remember me" option, they should be seamlessly authenticated or prompted for their credentials. Once successfully authenticated, the URL should redirect back to where the user intended to go.

Here's how it should ideally function:

http://example.com/page1 <-- user opens in new tab using ctrl+click
http://example.com/page2 <-- no active session for user
http://example.com/signin?url=/page2 <-- redirected to sign in before accessing page 2
http://example.com/page2 <-- user session restored post successful sign-in

If the user has opted for the "remember me" feature, the signin step can be bypassed.

Storing session tokens in localStorage is akin to not having sessions at all, as the token will persist even after browser restarts. This poses a significant security risk.

Answer №2

One potential solution to your new tab or new browser window issue could be setting the JWT in the cookies of your domain. By doing so, the cookie will be included in every GET/POST request fired from your application, offering a seamless resolution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to displaying components based on a function's conditions

I'm working on a component that needs to display certain elements based on a condition: export interface MyComponentProps{ children: ReactNode } export const MyComponent= (props: MyComponentProps) => { const [isInitialized, setIsInitialized] ...

What are the steps to refresh the content in a glightbox slider?

I'm currently utilizing Glightbox to set up a gallery that includes descriptions for images. I have a specific request where I want the button text to update on click. However, when the button is clicked and the lightbox reopens, the text on the butto ...

The "Mongoose 'model is not a constructor' error" is causing issues

It appears that I am encountering a rather common error. Despite reviewing previous questions, none have been able to resolve my issue. The typical mistakes involve using module.export instead of module.exports, and initializing a new schema instance inste ...

Hiding an image when pressing on a navbar icon: Tips and tricks

How can I toggle the visibility of an image when the bars icon is pressed on smaller screens, using CSS without JQuery or JavaScript? I have attempted to hide the image with visibility: hidden; in CSS but it does not work as intended. Please run this cod ...

Warning: The `children` attribute returned a value of NaN

I am currently working on a tic tac toe web application. I encountered an issue when clicking the "Ver Ranking" button, as it displays a warning message that I'm unsure how to address: Warning: Received NaN for the `children` attribute. If this is exp ...

Displaying image alt text on hover using pure JavaScript

Is there a way to hover over images on my webpage and display their alt text using vanilla javascript, without relying on jQuery? Here is the code for my images: <a href="<?php echo $displayData['href']; ?>" class="group"> <d ...

Storing a Mongoose value as a date: best practices

Whenever I store a date in Mongoose, it always gets saved as a string. let currentDate = new Date().toISOString(); let item = await Item.findOne({}); item.details.expiryDate = currentDate; await item.save(); After checking the database ...

Angular js encountered an unexpected error: [$injector:modulerr] ngRoute

https://i.sstatic.net/PATMA.png In my Angular code, I encountered the error "angular is not defined". This code was written to test the routing concept in AngularJS. var app=angular.module('myApp',['ngRoute']) .config(function ($routeP ...

Steps to retrieve an incorrect fruit when it is located as the initial item within the array

Currently tackling the precourse material for a coding bootcamp and hitting a roadblock with this particular question. Despite my best efforts, I just can't seem to meet one of the 7 conditions required. Let me outline the question, my attempted solut ...

Update 64 for Chrome - <video> tag's mute attribute not functioning as expected

Click here to view the code snippet <div ng-app="myApp" ng-controller="testCtrl"> <section ng-if="url"> <video id="player1" playsinline autoplay loop muted volume="0.0"> <source ng-src="{{url | trusturl}}" type="video/m ...

Guide on transferring JavaScript Objects from the Front End to Spring Boot Back-end and effectively processing and parsing them

After struggling with this issue repeatedly while developing my web apps, I've reached a breaking point and need some help. My frustration might come across as venting, but I'm genuinely stuck. The challenge I'm facing is sending key-value ...

Tips for positioning a button next to a text area

I am facing an issue with aligning my text area and button vertically on the same line. Despite my attempts, the button keeps getting pushed downwards. Can someone please provide me with a solution to align them properly? Thank you. Here is the HTML code ...

Declaration of an Angular module

I'm attempting to integrate the 'base64' module into my Angular page controller. Previously, I defined my controller in this way: angular.module('app').controller('newProjectController', newProjectController); After con ...

A guide on processing text line by line within a textarea and transforming it into JSON using AngularJS

Here is a textarea containing values in a specific format: param01 : value01 param02 : value02 This is the code I have tried: <div class="col-xs-4 input-container"> <textarea id="gateway-params" ng-disabled="!edit">{{gatewayParams}}</te ...

Press the button obscured by an image

Recently on my HTML website, I encountered an issue where I tried adding a transparent image over a button but found that I was unable to click on the button afterwards. The problem seems to be related to the following code snippet: #container { heigh ...

Obtain an indeterminate value from a variable

My situation involves a dynamic variable assigned from a service, requiring a real-time calculator to update another variable using its value. Below is the relevant code snippet: $scope.getSubTotalSCTax = function(){ TableService.checkOut('SubTo ...

What are the fundamental steps for setting up AJAX with a mongoDB server?

I need help with making an AJAX request to pull data from my database. I am looking for a simple example to check if a user exists before creating a new one. Currently, I am using mlabs and trying to understand how to access it through JavaScript. This p ...

The oddity of a lone quotation mark trying to break

var x = "Test \'" > undefined var y = "Test '" > undefined x === y > true x > "Test '" https://i.stack.imgur.com/ZrHo5.jpg Aha! Both of these strings are actually equal (as shown in the example code) - but why is that the ...

Using dynamic content in an Angular Material md-tab template allows for a more engaging and customizable

var app=angular.module('app',['ngRoute','ng-breadcrumbs','ngMaterial','ngAnimate','ngAria','ControllerModule']).config(['$routeProvider',function($routeProvider) ...

The date format in AngularJS is not being displayed correctly according to the request

My goal is to retrieve the date in the format of dd/MM/yyyy and pass it along to my URI. However, I am encountering an issue where the date is not being passed in the requested format. Below is the snippet of my HTML code: <script type="text/ng-templat ...