The Authorization Header sent by Angular is always null

I've been attempting to send a request with an authorization header using Angular to communicate with a Spring backend.

export class TokenInterceptor implements HttpInterceptor{

    constructor(public sharedService : SharedService){}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const jwtToken = this.sharedService.getJwtToken();

        if(jwtToken){
            req = this.addToken(req, jwtToken)
        }

        return next.handle(req)
   }

   addToken(req: HttpRequest<any>, jwtToken: any){
        return req.clone({
            headers: req.headers.append('Authorization', 'Bearer ' + jwtToken)
        });
   }
}

This is what my interceptor function looks like. Interestingly, when I try to console.log() the authorization header before returning the next().handle() method, I can see the correct token within the request. However, the issue arises when the backend receives a null Authorization header instead.

Within my backend, there is a doFilterInternal() method which filters any incoming requests and extracts the Authentication header. Despite enabling CORS on my backend, the problem persists.

@Override
public void addCorsMappings(CorsRegistry corsRegistry){
    corsRegistry.addMapping("/**")
            .allowedOriginPatterns("*")
            .allowedMethods("*")
            .allowedHeaders("*")
            .exposedHeaders("Authorization")
            .allowCredentials(true)
            .maxAge(3600L);
}

Answer ā„–1

In my opinion, the token is not being set because the headers property is considered to be read-only based on the documentation.

You can try utilizing the setHeaders property within the clone method argument like so:

addToken(request: HttpRequest<any>, jwtToken: any){
   return request.clone({
      setHeaders: { Authorization: 'Bearer ' + jwtToken }
   });
}

Answer ā„–2

After struggling for hours, I finally discovered the solution. When creating a new class and implementing WebMvcConfigurer to enable CORS, this should be the correct approach.

public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry corsRegistry){
        corsRegistry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .exposedHeaders("Authorization")
                .allowCredentials(true)
                .maxAge(3600L);
    }
}

However, simply implementing this in the WebConfig class was not sufficient. CORS also needed to be enabled in the security config chain.

@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        http.cors().and().csrf().disable();

    return http.build();
}

This can be achieved by adding http.cors()

Answer ā„–3

To address the problem, I successfully resolved it by modifying the base URL to ensure that HttpClient transmits requests through HTTPS rather than HTTP.

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 view in Angular after making changes to a list: A step-by-step guide

Iā€™m working with a view that includes the code snippet below: <div *ngIf="step" [sortablejs]="orderedId" [sortablejsOptions]="optionsSortable"> <div *ngFor="let item of step.items" class="item"> <div class="position">{{item.posit ...

Generate written output using a collection of C# class titles on a typewriter

I need help finding a setup or template file for creating TypeScript files based on a group of C# classes with Typewriter. Here's an example of what I'm looking for: $Classes(['myclass1','myclass2','myclass3'])[ ...

A streamlined approach to implementing driver.wait in selenium webdriver with Java

public class menupageProperty{ public static WebElement administrativeModule(WebDriver driver) { private static WebElement menuElement= null; menuElement= driver.findElement(By.linkText("ADMINISTRATIVE MODULE")); return menuElement; } publi ...

Implementation of a nested interface using a generic and union types

I am seeking to create a custom type that will enable me to specify a property for a react component: type CustomType<T> = { base: T; tablet?: T; desktop?: T; }; export type ResponsiveCustomValue<T> = CustomType<T> | T; This ...

Update the Angular material table with the set filtered results

Currently, I have a functioning Angular Material table with search capabilities. However, I am encountering an issue. The problem lies in the fact that when I navigate from 'route A' to 'route B' and pass a value to the search box in t ...

What could be the reason for the component not receiving data from the service?

After attempting to send data from one component to another using a service, I followed the guidance provided in this answer. Unfortunately, the data is not being received by the receiver component. I also explored the solution suggested in this question. ...

Capturing page titles accurately for timeonsite tracker in a single-page Angular app is challenging when navigating to other pages

Implemented the timeonsite JS tracker in my Angular web application using HTML tags as shown below, <script type="text/javascript"> var Tos; (function(d, s, id, file) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementByI ...

For proper completion of EnumHeader in a selenium cucumber integration scenario, make sure to include "enum Identifier"

I am looking to incorporate cucumber into my selenium feature files Feature: Testing the smoke test of Facebook Scenario : Test FB with valid credentials Given Open browser and start application When I provide valid username and password T ...

Encountering an "Unexpected token" error when importing a JSON file in TypeScript even though the JSON is valid

I recently read an article on Hacker Noon about importing JSON into TypeScript, and decided to give it a try in my code. Here's the import line I used: import data from './assets/fonts/helvetiker_bold.typeface.json'; To test if the import ...

What steps can I take to generate a JSON array with this unique format?

The data I received from my angular form is in the array format: [{"name":"Rose","number":"+919224512555"},{"name":"smith","number":"+91975555224"}]. The data represents a dynamic table with columns for name and number. I need to convert the array above i ...

Using annotations on a POJO object to create a BeanPropertySqlParameterSource

Here is the issue I am facing: @Data //Lombok annotation to generate getters and setters @Entity public class TradeLog { @Id @Column(name="P_TRADE_ID") private String tradeId; } tradeLog.setTradeId("1"); SqlParameterSource insertParam = new B ...

"How can we trigger a re-render of a React component once a promise is fulfilled? Is there a way to prevent rendering until the

Having attempted to make updates to a functional component that interfaces with an azure-devops-ui/Filter, I've encountered a situation where I am utilizing the azure-devops-extension-sdk to handle async responses. This component is intended to be use ...

Is there a way to generate a result based on a comparison of two lists?

Having two lists, Alpha and Beta, stored in separate files. The values are originally tab-separated, but for display purposes they are separated with an equal sign. Alpha: x=1 y=2 z=3 Beta: y=2 a=1 x=1 z=4 The desired output format is as follows: Alp ...

Understanding Type Syntax: Exploring the Significance of Syntax in Typescript

I'm unfamiliar with Typescript and struggling to grasp the significance of this syntax. Could someone provide some clarification? type Type1<K> = K extends string ? { [P in K]: string } : never; If type K is a subclass of string, does that mea ...

An issue occurred when clicking on a line due to the filter

Issue at Hand: Currently, I am facing a problem where selecting an item from the list by clicking on the button leads me to access the information of a different item when the filter is applied. Desired Outcome: I wish to be able to access the correct inf ...

Why is it so difficult for the TypeScript compiler to recognize that my variables are not undefined?

Here is the code snippet in question: function test(a: number | undefined, b: number | undefined) { if (!a && !b) { console.log('Neither are present'); return; } if (!b && !!a) { console.log('b is not present, we ...

What is the best way to retrieve a PID from a Process that was spawned using the TS Exec Function

When working on a Windows system with TypeScript I face an issue with a function that launches another application via the command line. I am able to capture the Pid spawned by this Exec Function, but it turns out to be the Pid of the CMD used to initiate ...

Assign an appropriate label to this sonarqube input field

Sonarqube flagged an issue with the following line of code: <div class="dropdown-language"> <label>{{'GENERALE.LINGUA' | translate }}</label> <select #langSelect (change)="translate.use(langSe ...

Develop a custom cell editor for ag-Grid and insert it into a designated location within

I am currently working with Angular 16 and AgGrid 30. My goal is to have the cell editor created in a different location than its default position, which is within a div element at the bottom of the body with these classes: ag-theme-material ag-popup. I w ...

Angular 6 application experiencing an issue where the browser console is not displaying an error that says "Cannot GET /

I was tasked with making modifications to an Angular 6 web application, which I hadn't worked on before. After receiving the source code, I attempted to display the website but encountered errors. I spent late nights and early mornings trying to succe ...