Angular form requests can utilize the Spring Security Jwt Token to allow all options methods

Despite checking numerous sources online, I am facing a persistent issue with my Angular application. The problem arises when using HttpClient along with an Angular interceptor to set headers for authentication in my Java Rest API using JWT tokens. The interceptor seems to malfunction, resulting in the Java side receiving a null token and generating errors. Any assistance would be highly appreciated.

Upon closer inspection, it appears that the root of the issue lies within Spring Security. After debugging, it was revealed that the options request all filter lacks the necessary header, ultimately causing token-related exceptions. Potentially allowing bypass for option method requests could resolve the problem.

Snippet of the Spring Boot Security Configuration:

(Security Config code here)

Code snippet of the Angular Interceptor:

(Angular Interceptor code here)

Code snippet of the Angular Service:

(Angular Service code here)

Method Call:

(Method call code here)

Browser Network Results:

Local Storage for Token:

Error Message in Browser Console:

Error Message from Spring Boot Java Console:

Answer №1

In the JwtSecurityConfig file, it is important to include the OPTIONS call in order for the JWT security to work properly without requiring an authentication token.

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable()
            .authorizeRequests()
            // Ensure this line is included in your implementation
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .antMatchers("**/rest/**").authenticated()
            .and()
            .exceptionHandling().authenticationEntryPoint(entryPoint)
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    http.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    http.headers().cacheControl();

}

Answer №2

While the Angular interceptor may seem like a good solution, there seems to be a CORS policy error in your browser console. Your Angular application is running on port 4200, while your backend is running on port 8095 (different hosts).

I am not familiar with spring-boot, but after reviewing the documentation, it appears that you need to add some CORS policies to the backend application. These policies may differ for production and development environments:

For more information, you can refer to this link:

Currently, your request to /allUser is not being sent. Once you resolve the CORS issue, everything should function properly.

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

Refreshing the page after making an API call does not result in updated data

Within my VueJS application, I have implemented an API call to retrieve user statistics for display. The process involves a straightforward Java backend and utilizing an $axios get request. Upon initial page load, everything functions as anticipated. Howev ...

Improving Angular 2 Charts with Multiple Chart Updates

Looking for some help with my code. I am fetching server data using an API for monitoring purposes and have multiple charts set up. The issue is that only the first chart updates every second when I call the API, but the others do not update. Any suggestio ...

Break up every word into its own separate <span>

I am currently facing an issue with displaying an array of strings in HTML using spans. These spans are wrapped inside a contenteditable div. The problem arises when a user tries to add new words, as the browser tends to add them to the nearest existing sp ...

Using the locale identifier en-GB can lead to date formats being displayed incorrectly

I'm struggling with setting up the correct locales in my Angular application. As per the documentation, I've inserted the following code snippet into my angular.json file. "projects": { "appname": { ..., "i18n&q ...

The variable "theme" is referenced prior to being initialized

https://i.stack.imgur.com/QL0pa.png One of the variables in my code, theme, is set to be assigned a value from a for loop: let theme: Theme for (const themeObj of themeList) { const [muiThemeName, muiTheme] = Object.entries(themeObj)[0]!; if (muiThem ...

End the pipeline execution in a chain of RxJS observables

Here is a scenario where a series of Observables are chained together. Is it possible to prevent the subsequent chain from executing if an error is thrown by 'parentObs1'? import { throwError } from "rxjs"; import { mergeMap, catchError ...

Attempting to create a function that can accept two out of three different types of arguments

I am trying to create a function that only accepts one of three different types type A = 'a' type B = 'b' type C = 'c' The function should accept either type A, C, or both B and C, but not all three types. This is what I hav ...

Modifying the interface state in React with TypeScript is not permitted

I encountered a compilation error in the code below, where I am unable to modify the state in closeLeftCol function. The error message states: Cannot assign to leftWidth because it is a constant or read only property: interface ILayoutState{ r ...

Utilizing a class structure to organize express.Router?

I've been playing around with using Express router and classes in Typescript to organize my routes. This is the approach I've taken so far. In the index.ts file, I'm trying to reference the Notes class from the notes.ts file, which has an en ...

Angular - Monitoring Changes in Variables

I've recently started working with Angular, primarily using VueJS. I'm curious about how to detect when a variable is updated. In my case, the variable is being updated through a DataService. I came across ngOnChanges(), but it seems that it only ...

Unable to access the correct item from local storage while a user is authenticated

I am facing an issue with retrieving the userid from local storage when a user is authenticated or logged in. The user id is not being fetched immediately upon logging in, and even when navigating from one page to another, it remains unavailable until I re ...

The implementation of the new package is causing a disruption in my project

I've encountered an issue while trying to integrate bcryptjs into my application. Although I successfully installed it, the development environment crashes upon startup. The project is currently built on angular v6, and after running npm install to do ...

Tips for verifying the presence of a value within an array using checkboxes

My firestore database contains a collection named world with a sub-collection called languages I have developed two functions: one to retrieve all documents from the sub-collection languages, and another function to fetch every language if the userUid val ...

Utilizing dispatch sequentially within ngrx StateManagement

I have been working on a project that utilizes ngrx for state management. Although I am still fairly new to ngrx, I understand the basics such as using this.store.select to subscribe to any state changes. However, I have a question regarding the following ...

What is the best way to ensure observables in a template (using async pipe) are fully subscribed to before executing any initialization code?

I am facing an issue with my HTTP service that returns information based on a given item ID. The data is fetched using a Subject, which receives the initial data in the ngOnInit method. To display the returned data in the HTML, I utilize the async pipe. ...

Why does it seem like Typescript Promise with JQuery is executing twice?

Figuring out Promises in Typescript/JS seemed to be going well for me, but I've hit a roadblock. I've set up Promises to wait for two JQuery getJSON requests to finish. In my browser, when connecting to a local server, everything functions as ex ...

Combine arrays of objects by comparing two attributes in Typescript

Suppose I have an array in TypeScript that looks like this: const array = [ { id_m: "123", period: "Q1/22", amount: 1000 }, { id_m: "123", period: "Q1/22", amount: 500 }, { id_m: "123&q ...

Only the final defined document is instantiated by the Swagger-ui-express module

Currently, I am working on a Typescripted nodejs server and facing an issue with defining different swagger paths for separated controllers. The problem is that the swagger-ui-express module only displays the last defined document in the specific route. I ...

Can someone guide me on incorporating static methods into a Mongoose model using TypeScript for Mongoose version 5.11?

When using Mongoose 5.10, I implemented static methods in my Mongoose models with the following pattern: import { Schema, Document, Model, Connection } from "mongoose"; import { v4 } from "uuid"; export interface IFoo extends Document ...

Sending properties of an element to a function within Angular version 4 or 5

Trying to pass attribute values of elements to a function on button click, this is my approach: <div> <ul #list> <li class="radio" *ngFor="let option of options; let j = index" id={{i}}-{{j}} #item> <label><input t ...