Spring Security does not generate an error if the authorization header is missing following a login using AngularJS

Working on implementing HTTP Basic Authentication using Spring Security and Angular JS by including the Authorization header in $http headers:

const headers = {
    authorization: "Basic " + btoa(this.login + ":" + this.password)
};

this._$http.get("user",
    {
        headers: headers,
    })
    .then(
        this.showUser.bind(this),
        this.showError.bind(this)
    );

After successful login, I navigate to the jobs component using $location:

this._$location.path("jobs");

In the jobs component, I retrieve available job listings:

public $onInit() {
    this._$http.get("jobs").then(function(response) {
        this.jobs = response.data;
    }.bind(this));
    this.authenticated = this._loginService.isLogged();
}

Interestingly, even without an authorization header, the functionality seems to work. I expected Spring Security to respond with HTTP 401 Unauthorized, but it still worked flawlessly. However, upon logging out from another browser window and reloading the jobs, they are not loaded. This raises concerns about whether the authorization data (HTTP Basic) should be included in all requests. Here is a snippet of my security configuration:

protected void configure(HttpSecurity http) throws Exception {
    http
        .formLogin()
        .successHandler(
            new DifferentRoleBasedStartingURLsAuthenticationSuccessHandler()
        )
        .and()
        .logout()
        .logoutUrl("/logout")
        .and()
        .httpBasic()
        .and()
        .authorizeRequests()
        .antMatchers("/jobs/**").authenticated()
        .antMatchers("/interviews/**").authenticated()
        .anyRequest().permitAll()
        .and()
        .csrf()
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    ;

I am uncertain if I made an error here. I believed that the rule

.antMatchers("/jobs/**").authenticated()
should also apply to jobs/. Any suggestions or assistance would be greatly appreciated. Thank you.


UPDATE 2016-07-31: I am starting to question whether authorization headers are truly necessary for every request in Spring with Angular integration. You can find my repository here, with the password set as test for all user accounts created.

Answer №1

If you're utilizing Basic Authentication, it may be redundant to also set up form login in the Spring framework. With basic authentication, the http Authorization header must be included with each request that requires authentication on the server. If an authorization header is missing for a protected resource, Spring will respond with a 401 error.

While your configuration seems correct (and yes, "/jobs/**" matches "/jobs"), it's possible that your test failed because the server assigns a jsessionid cookie which can still authenticate you even without an Authorization header for a protected resource.

To prevent spring-security from interacting with the http session, consider setting the session creation policy to STATELESS.

You can experiment with the following security setup:

protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers("/jobs/**").authenticated()
            .antMatchers("/interviews/**").authenticated()
            .anyRequest().permitAll()
            .and()
            .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .and()
            .sessionManagement()
           .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and();
}

Answer №2

The sequence in which security configurations are set up determines the order of rule application by Spring Security. If you initially restricted access to a pattern and then allowed it again using .anyRequest().permitAll(), you may encounter unexpected behavior. Below is the updated code with the corrected order:

http
    .formLogin()
    .successHandler(
        new DifferentRoleBasedStartingURLsAuthenticationSuccessHandler()
    )
    .and()
    .logout()
    .logoutUrl("/logout")
    .and()
    .httpBasic()
    .and()
    .authorizeRequests()
    .antMatchers("/jobs/**").authenticated()
    .antMatchers("/interviews/**").authenticated()
    .anyRequest().permitAll() // Corrected order
    .and()
    .csrf()
    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
;

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

I would greatly appreciate some guidance on asp.net and javascript

I am just starting out with JavaScript and facing some challenges. Currently, I'm struggling to develop a Mouseover and mouseout script. Here is my ASPX code: <div> <div id="div_img" style="height: 300px; width: 300px; border: solid 1p ...

Recursive sorting and parsing of JSON data with multiple levels

I'm new to using recursion in JavaScript and need some guidance to understand it better. I have a JSON data structure with multiple levels of nested "subcategories". const STORE_CATEGORIES = [{ "Id":"1", "Name":"One Parent", ...

Issue with Alignment of Border in PDF [Example Included]

I am currently developing a straightforward react application with very minimal content. index.js: <div className="App"> <div id="printable-div"> <h1>Generate PDF</h1> <p>Capture a screenshot of ...

Establishing Node.js environment variables when invoking `npm run` command

package.json { "scripts": { "start": "NODE_ENV=development node ./index.js" } } If we wanted to pass and override NODE_ENV when running npm run start, is it possible? npm run start NODE_ENV=production ...

Progressive Web App with Vue.js and WordPress Rest API integration

When creating an ecommerce website using Wordpress, I utilized Python for scraping data from other websites to compare prices and bulk upload products through a CSV file. My next goal is to learn Vue and transform the website into a PWA as it will be esse ...

The ng-repeat directive adds an additional line after each iteration of the list item

Whenever the angular directive ng-repeat is utilized with an <li> element, I notice an additional line appearing after each <li>. To demonstrate this issue, see the simple example below along with corresponding images. Here is a basic example ...

Issue with the reload animation jumping too quickly in Framer Motion on NextJS

While creating an animation for my landing page using NextJS with framer motion, I encountered a strange behavior after deploying the site. The animations started to happen too quickly and it felt a bit off. During development on localhost using Chrome, ev ...

Consistently Incorrect Date Formatting in Bootstrap Display

I have a potential issue with my date display. It should show a default "Start Date" in a short date format, but when the "Sale Date" DropDownBoxFor is toggled, it should display an AJAX result date. However, the display always appears in a date and time f ...

What could be causing the submit button to reactivate before all form fields have been completed?

I have implemented the code snippet below to validate each field in my contact form using bootstrap-validator and an additional check through Google reCAPTCHA. You can view and test the form here. The submit button is initially disabled with the following ...

What is the method for determining the number of unique tags on a webpage using JavaScript?

Does anyone have a method for determining the number of unique tags present on a page? For example, counting html, body, div, td as separate tags would result in a total of 4 unique tags. ...

Objects remaining static

I'm currently working on a VueJS component that has the ability to export data into .xlsx format. To achieve this functionality, I am utilizing the json2xls library, which requires an array of objects with identical keys (representing column names) to ...

Rails: Parameters are displayed in the console but cannot be accessed via params

I sent a get request to the following url: groups/:id.json Upon checking my Rails server console, this is the output: Processing by GroupsController#show as JSON Parameters: {"id"=>"11"} However, despite these parameters being passed, I am unable t ...

Discover the method for retrieving information through AJAX requests and dynamically displaying or hiding content based on the received

Currently, I'm in the process of developing a PHP script that outputs a numerical value indicating the number of unread messages. The snippet below showcases my code that triggers the PHP function every 30 seconds: setInterval(function (){ ...

Discover the most frequent value in an array by utilizing JavaScript

My array contains repeating values: [0, 1, 6, 0, 1, 0] How can I efficiently determine the highest frequency of a specific value being repeated? For example, in this array, I would like the script to return 3 since the number 0 repeats most frequently a ...

Hiding content and troubleshooting video playback problems in FancyBox

I'm facing an interesting issue. I've implemented FancyBox lightbox to showcase a "video" tag when users click on the image thumbnail, and it functions well with all varieties of HTML5 video. The challenge arises when testing in browsers older th ...

Animating Divs with jQuery to Expand their Size

I am currently designing a services page for my portfolio website. The layout consists of three columns, with the central column containing a large box and the left and right columns each containing three smaller boxes. These smaller boxes function as clic ...

Enhancing user privacy in Angular application with Web API integration and ASP.NET Identity

Currently, I have an AngularJS application that is connected to an ASP.NET Web API backend with OWIN/token-based authentication. The backend utilizes ASP.NET Identity for user registration and login functionalities. Both the frontend and backend are inte ...

Express session not persisting following JQuery Get request

I need to save the server variable that the user inputs. Once they submit, they are directed to another page. On this new page, I check if their server exists and redirect them back if it doesn't. When I make a post request, the session is saved, and ...

What is the best way to adjust the width of a navbar using JavaScript?

I am experimenting with a responsive design and facing an issue - the width of my #menu in CSS is initially set to 0, but I need to change this value based on user input using JavaScript. Now, I want to dynamically adjust the width of the menu for differe ...

The HTML function transforms blank spaces into the symbol "+"

Just starting out with a question: I created a basic submission form, but I noticed that if there are any spaces in the inputs, the values get changed to a plus sign (+). Here's my form: <form name="input" action="search" method="get"> Web Ad ...