What are the steps for combining AngularJS with Java JAAS authentication system?

My web application combines AngularJS on the frontend with Java on the backend. Angular communicates with the Java backend through Restful webservices exchanging JSON data over HTTP. I am in need of developing an authentication mechanism for this app and I'm exploring the best approach to take. Currently, I am utilizing JAAS-based authentication with a JDBC user table setup. Here is how my app is configured:

In my web.xml configuration, I have defined:

    <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>userauth</realm-name>
        <form-login-config>
            <form-login-page>/login.html</form-login-page>
            <form-error-page>/loginError.html</form-error-page>
        </form-login-config>                
    </login-config>

    <security-constraint>   
        <display-name>ConstraintSSL</display-name>
        <web-resource-collection>
            <web-resource-name>protected</web-resource-name>
            <description/>
            <url-pattern>/checkout/*</url-pattern>
            <url-pattern>/login/*</url-pattern>
            <url-pattern>/login.*</url-pattern>
            <url-pattern>/account/*</url-pattern>
            <url-pattern>/ad/create</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>HEAD</http-method>
            <http-method>PUT</http-method>
            <http-method>OPTIONS</http-method>
            <http-method>TRACE</http-method>
            <http-method>DELETE</http-method>
        </web-resource-collection>

        <user-data-constraint>        
          <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>        
    </security-constraint>

    <security-constraint>   
        <display-name>ConstraintUser</display-name>
        <web-resource-collection>
            <web-resource-name>user</web-resource-name>
            <description/>
            <url-pattern>/account/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>HEAD</http-method>
            <http-method>PUT</http-method>
            <http-method>OPTIONS</http-method>
            <http-method>TRACE</http-method>
            <http-method>DELETE</http-method>
        </web-resource-collection>
        <auth-constraint>       
            <description/>
            <role-name>ADMINISTRATORS</role-name>
            <role-name>USERS</role-name>
        </auth-constraint>

        <user-data-constraint>        
          <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>        
    </security-constraint>

    <security-role>
        <description/>
        <role-name>USERS</role-name>
    </security-role>
    <security-role>
        <description/>
        <role-name>ADMINISTRATORS</role-name>
    </security-role>

  <session-config>
    <session-timeout>30</session-timeout>
    <tracking-mode>COOKIE</tracking-mode>
  </session-config>

   <welcome-file-list>
    <welcome-file>init.html</welcome-file>
   </welcome-file-list>

The init.html page simply redirects to an index.html which loads Angular and initiates the app.

Below is my UserController responsible for managing user activities on the client-side (browser):

myControllers.controller('UserController', ['$scope', '$routeParams', 'UserService',
  function($scope, $routeParams, UserService) {
    $scope.logged = false;

    // Checking if User is detected from cookie
    $scope.user = fetchUserFromCookie();

    if (! $scope.user) {

        // Setting default guest user
        $scope.user = {         
            firstName : 'guest',
            lastName : 'user',
            preferredCurrency : "USD$",
            sessionHash: "XXXXXX",
            shoppingCart : {
                totalItems : 0,
                total : 0
            }           
        };      

    }

    $scope.login = function(userName, pass) {
          $scope.user = UserService.login(userName, pass);            
          $scope.logged = true;      
    };

    $scope.logout = function(userName) {
          $scope.user = UserService.logout(userName); // notifying server of logout
          $scope.logged = false;
          $scope.user = null;
    };

  }]);

My aim is to create a login page with JAAS-based JDBC authentication, permitting only users with specific ADMIN or USER roles to access certain pages. How can I achieve this in an AngularJS + Java environment?

  • I am particularly concerned about session tracking,

  • ensuring that authorized users have the necessary permissions to modify specific records,

  • and preventing manual hacks such as altering JS code or manipulating cookies to hijack a user's session.

Answer №1

  • Token should be embedded within the HTML of the index.html page to prevent CSRF attacks.
  • Avoid storing the token in a cookie storage for security reasons.
  • Every request must be signed with a header parameter for authentication.
  • The server needs to verify each request by checking the passed header information.
  • If using cookies is necessary, ensure to validate the referrer to mitigate CSRF risks.

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

Placing a Fresh Item into a Designated Slot within an Array

Imagine having a MongoDB collection that consists of an array of objects being retrieved from an Angular Resource. [{_id: "565ee3582b8981f015494cef", button: "", reference: "", text: "", title: "", …}, {_id: "565ee3582b8981f015494cf0", button: "", ref ...

Is it possible to show one element while hiding others upon clicking using JavaScript?

Concept My idea is to create a website with a navigation menu where only one section is visible at a time. Each section would become visible upon clicking a specific button in the navigation bar. Challenge I attempted to achieve this using the following ...

Learn how to verify the existence of a URL or webpage using AJAX or jQuery

When a user is creating a profile, they have the option to include links to their websites or blogs that will be displayed on their profile page. Before saving these links to the database, I would like to verify if the provided URL exists. Is there a meth ...

SheetJS excel-cell customization

I'm using this example to export a worksheet from https://github.com/SheetJS/js-xlsx/issues/817. How can I apply cell styling such as background color, font size, and adjusting the width of cells to fit the data perfectly? I have looked through the do ...

How can an object inside an array be destructured in just one line?

Consider the following array: const array = [{b:2}] Can you extract the value of b using destructuring in just one line? I attempted something similar to this approach, but it did not yield the desired result: const [{b} = array] ...

Issue with Nativescript tab view not functioning as expected

I have encountered a bug while manually trying to change tabs. The issue arises when the tab index changes but the tabs themselves do not update accordingly. In order to demonstrate this problem, I have created a NativeScript Playground app where you can ...

Condition formulation using dynamic dust JS equality

I'm struggling with a seemingly simple task - dynamically changing the @eq condition. The example provided shows a default render, but what I really need is to allow user input to change it to either "Larry" or "Moe". You can view my code on jsfiddle ...

Error: The function $.get is not recognized when using jQuery with babel-node

Currently, I am executing the code below from a test.js file using babel-node in the command line: babel-node test.js installation of jquery npm i --save jquery test.js: import $ from 'jquery'; $.get("www.google.com"); Upon execution, I en ...

Convert an array to a string using a JavaScript function

I am encountering an issue with the code below: Every time I pass the Array to "track," I encounter an error. It seems like there might be a mismatch between passing an object and a string as input, but I am uncertain and unable to verify. for (var i = 0; ...

The information retrieved from the open weather map API is difficult to interpret

Currently experimenting with the Open Weather Map API. Two specific calls are being examined, one for London and another for Hermanus in South Africa. Noticing differences in the data returned from each call. Below are the two API calls: Data returned fo ...

What is the best method for inserting a 'Placeholder' in an Angular datePicker?

Looking for assistance with placing placeholder text inside an Angular datePicker, specifically wanting to display 'From' and 'To' labels within the datePicker. datePicker I am a novice when it comes to Angular development - can someon ...

The HTML div captured with html2canvas is incomplete

I am currently developing a meme editor website utilizing the html2canvas library available at Below is the HTML code for the div I aim to capture: <div class="container"> <div id="theUserMeme"> <div class=& ...

Having trouble retrieving data from MongoDB and rendering it on an HTML page

Creating a Model Named Field.js in Mongoose const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/SuperchainV1', { useNewUrlParser: true }); mongoose.set('useNewUrlParser', true); ...

When passing an object to a function inside a promise.then, Typescript may generate an error indicating that the object could

Snippet of code below is extracted from a request controller function. Goal The aim was to generate various notifications based on the paths that are modified. let farmerToUpdate = await FarmerModel.findById(farmerId) if (!farmerToUpdate) throw new cont ...

Conceal the parent component's <button> element within the Child component

I'm facing an issue with hiding a button in my parent component from the child component. I tried using props to bind the element and v-show directive to hide it, but instead of just hiding the button, it ends up hiding the entire tab. Take a look at ...

Leveraging an external script for enhanced functionality in React/Meteor application

I'm currently facing a challenge incorporating an external script into my React component within Meteor. I've experimented with directly placing the script tag in my component as follows: TheLounge = React.createClass({ render() { return ( ...

Utilizing Supabase queries alongside React's Hot Toast Promise: A Comprehensive Guide

I'm currently working on an admin panel to manage my website. As part of the development, I am using Supabase for the Database and React Hot Toast for notifications. Recently, I attempted to implement Toast Promise using the following code: const add ...

Utilizing a filter within the ng-model directive

I have a question about using a filter with an h3 element. Here is the code snippet: {{ event.date | date:'dd-MM-yyyy' }} It's working perfectly fine and Angular is formatting the date as expected. However, when I try to use the same filte ...

Jquery Enhancement for Navigation

Recently, I have implemented a header and footer navigation on my website. The header navigation consists of 1 UL (unordered list), while the footer navigation comprises 5 ULs. My goal is to align the first child of each UL in the footer navigation with th ...

Invoke function within bxslider callback

I am attempting to utilize a custom function within a bxslider callback, but unfortunately, the function is not being recognized (specifically: Uncaught Reference Error: nextSlideCustom() is not a function) The current code snippet I have is as follows: ...