Angular-powered SPAs with cookie authentication

My current web framework utilizes cookie (or token) based authentication. Upon user registration, a postback occurs and the server embeds an authentication token into a cookie which is then linked to the user's browser. Subsequent requests utilize this token, ensuring security.

Inquiry: Is it necessary to perform a full-page postback refresh after user registration in order to place the auth-token on the user's browser? Or is it possible to have the server send back an auth token (via ajax) upon successful user registration (which is also done via ajax)? I would prefer the latter option if feasible.

Thank you.

Answer №1

To ensure your framework includes a token, simply incorporate it into the headers of all subsequent requests.

If you want this token to be permanent, additional code is necessary (such as storing it in localStorage).

While I may not know the specific Header required by your framework, I can help you visualize how your login controller might appear:

angular.module('coolModule', [])
.controller('CoolController', function ($scope, $http) {

  $scope.loginButton = function () {

    // assuming username and password are in the scope
    $http.post('/api/login', { $scope.username, $scope.password })
    .success(function (data, status, headers, config) {
      $http.defaults.headers.common['X-My-Token'] = data.token;
    });

  }
})

Subsequent requests will now include an X-My-Token header for identification purposes.

EDIT: Implementing a cookie (either through JavaScript or via server response) ensures its inclusion in every request, similar to other cookies on the internet.
For a more elegant solution, particularly if you're also developing the backend, having the backend send a cookie to the client is recommended instead of manually writing it as you mentioned ^_^

A cookie offers certain advantages, such as an expiration date, but also comes with drawbacks like the complexity of reading it from JavaScript (often necessitating a wrapper library like angular-cookie for compatibility across browsers).

In cases where the cookie expires or the token becomes invalid (resulting in a 40x response), handling the failure will require some Angular.js coding.

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

Determining the length and angle of a shadow using X and Y coordinates

I'm currently tackling the task of extracting data from a file generated by a software program that has the ability to add a shadow effect to text. The user interface allows you to specify an angle, length, and radius for this shadow. https://i.stack ...

What is the process of extracting a value from an array of objects based on another parameter?

Given the array below which contains objects with nested arrays, my goal is to retrieve the value 'AUS Eastern Standard Time' when 'Australia/Melbourne' is passed to the array. Although I attempted to use the code var winTimeZone = arr ...

Guide on transferring object between two $states using ui-router

Visit this link for more information Expected Behavior Upon logging in, selecting a Ticker button is expected to trigger the display of matching Tags for that specific Ticker. Actual Results However, upon clicking a Ticker button after logging in, the ...

I'm having trouble understanding why I can't redirect to my GET router after making a POST request

profile.ejs <body> <div id="box"> <h1>Greetings, <span><%= user.name %></span>!<hr> How are you feeling today?</h1> <!-- <form action="/users/logout" method=" ...

Struggling to set up server-sent events and event sources in JHipster

I am currently working on building an application using JHipster 3.5.0 with spring-boot and angular. I want to implement server-sent events to send updates from the backend to the UI, but I am facing issues getting it to work. Below is the code snippet of ...

JavaScript hard-coded object functions as an argument, however it does not reference the global object

Recently, I encountered a strange issue while working with JQuery Flot. Initially, my code looked like this: var plot = null; function initPlot () { plot = $.plot("#graph", myData, { /* my options here */ }); } and everything was functioning correc ...

Transform asynchronous calls into synchronous calls

During my time building web applications in PHP, I was accustomed to handling tasks synchronously. Currently, my focus is on constructing a web scraper. The process involves: Obtaining a list of proxies Verifying the status of the proxies Scraping web c ...

React-Redux Error: The function this.props.AppendCharacter is not defined

I have been looking for a solution to my issue but couldn't find anything that matches it. I am working on creating a calculator app using React & Redux, and whenever I click on one of the number buttons, I receive an error message saying "this.props. ...

The jQuery load() callback triggering a POST request unexpectedly instead of a GET request

Utilizing jQuery's load() method, I am attempting to insert a page fragment into a new page. It appears that this can only be achieved with load(), as get() does not support page fragments. Upon completion of the load, it is necessary for me to invok ...

Error: The 'length' property cannot be searched for using the 'in' operator

Hmm, I keep getting an error that says "Uncaught TypeError: Cannot use 'in' operator to search for 'length' in" Every time I attempt a $.each on this JSON object: {"type":"Anuncio","textos":["Probando ...

Creating objects based on user input in AngularJS is a common task for developers. This tutorial will

When populating a form with radio buttons based on a JSON object, the user can select options and upon clicking submit, all radio button data is saved into an object. <form name="regForm"> <ul> <li ng-repeat="q in ...

Ways to utilize the map() function with data retrieved from an axios response?

Utilizing axios for data retrieval from the server and then storing it in the state. However, when attempting state.map( post => {console.log(post)} ), no output is displayed. The technologies being used are Express, Mongoose, NextJS, and Axios. My ap ...

JavaScript 'this' pointing to incorrect object

Unfortunately, this doesn't seem to be pointing to the correct object in this scenario. I'm having trouble figuring out how to reference the right one. function myObject() { this.someMethod1 = function() { var elementBtn = document.getEl ...

What is the best way to conceal a callback form once it has been successfully submitted?

In my callback form, everything seems to be functioning properly. However, there is a slight issue when the client hits the submit button multiple times. Each time they do so, a notification saying "Your request sent successfully" pops up next to the butto ...

Steps to stop an AngularJS $timeout when a user leaves the page

In my angularjs app, I utilize the $timeout function to regularly refresh information on a certain page. However, I am looking for a solution to cancel the $timeout when a user decides to leave this page. Is there an easy method to achieve this? ...

Is there a way for me to assign values to my array within each loop when the inner elements vary?

Every time I work on this JavaScript code, I feel like I'm close to finishing it but then encounter another obstacle. My goal is to extract values from different elements such as <input type="text"> and <select>. Here's the code snipp ...

Setting up package.json to relocate node_modules to a different directory outside of the web application:

My web app is currently located in C:\Google-drive\vue-app. When I run the command yarn build, it installs a node_modules folder within C:\Google-drive\vue-app. However, since I am using Google Drive to sync my web app source code to Go ...

Guide to importing an npm package into a client-side file

Having some trouble importing the js-search npm package into my client-side .js file. The documentation suggests using import * as JsSearch from 'js-search';, but I keep getting a Uncaught TypeError: Failed to resolve module specifier "js-se ...

Using Reactjs to Send Emails

Trying to incorporate the SmptJs API for email sending using JavaScript has been quite successful in a simple HTML setup. However, I am facing challenges when attempting to integrate it into a ReactJs component! The API documentation and link can be found ...

Enhancing game menus for various mobile screen sizes

I've noticed a consistent pattern in the games I download from the Google Play Store - they all have a background image at the menu with clickable buttons. When testing these games on different devices, I found that the backgrounds didn't stretch ...