Using Angular with OAuth2 in conjunction with reactive Spring Security

I am currently working on implementing social login functionality with VK for my Angular application and Spring Webflux backend. Right now, I have an endpoint in the backend to retrieve user information: localhost:8080/people/me. I attempted to authenticate the user on the frontend as follows:

ngOnInit(): void {
    this.http.get(USER_INFO_URL)
      .subscribe((resp: Response) => {
        if (resp.status < 300) {
          this.authenticated = true;
          resp.json()
            .then(vkUser => {
              let fields: [string, string] = ['firstName', vkUser.firstName];
              fields['lastName'] = vkUser.lastName;
              this.user = new User(vkUser.id, fields);
            });
        } else {
          window.location.href = AUTH_URL;
        }
      });
  }

However, when my Spring application redirects the client to VK for authentication, VK does not provide any CORS headers, resulting in the authentication process failing.

Can someone suggest a method for utilizing OAuth2 with Angular/Spring combination? Since I am utilizing a code flow, I assume that I first need to obtain the code on the frontend and then send it to the Spring backend to exchange it for an access token.

Additionally, I am considering the possibility that my approach may be incorrect and that the entire authentication process should occur on the backend, while the frontend simply receives a cookie. However, I am unsure how to redirect AJAX requests from the frontend to the VK login page, manage it on the backend, and then return to the Angular application.

Answer №1

To make this work, you'll need to either set up third party software that allows cross-origin requests from your website or incorporate server-side API code into your app for the login process.

From our conversation in the comments, it seems like you already have a successful login flow established over a couple of request cycles. You can utilize this same flow to obtain a valid session and then redirect to your single-page app. Ensure that the cookie is configured as an HTTP only cookie to prevent unauthorized access by JavaScript. This setup will enable you to send requests to your server without needing extra authentication parameters. Just remember to validate the cookie during API requests and create handling logic to prompt the user to log in again if the cookie is missing or no longer valid.

I hope this explanation clarifies things for you!

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

Only numerical values are permitted, and numbers may not commence with 0 in Angular 4

Hey there, I'm new to Angular 4 and in need of help validating a form field. I want to allow only numbers, but the first digit should not be 0. I've tried different solutions that I found, but none of them worked for me. Could someone please as ...

`ìf the navigation button is clicked, the onSlideChange function runs twice`

For my project, I implemented multiple slides per group using Swiper.js and React@^18. However, I encountered an issue where the onSlideChange function runs twice when clicking the navigation button at the first slide's group. This causes it to skip t ...

What is the best approach to obtain a Generic and static reference to a MongoDB collection?

My goal is to create a generic and static class method called getOne<T>() that can return MongoDB objects as an Item, where the Item can be either a Book or a Film. Initially, I had an idea on how to achieve this, but now I am struggling with dynamic ...

Having trouble sending a JSON object from Typescript to a Web API endpoint via POST request

When attempting to pass a JSON Object from a TypeScript POST call to a Web API method, I have encountered an issue. Fiddler indicates that the object has been successfully converted into JSON with the Content-Type set as 'application/JSON'. Howev ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...

Issue regarding the Angular Material module

I recently added @angular/material to my project, using version @6.2.1. However, I encountered an error when trying to import this module in my app.module.ts file. The error message reads: "Module 'c:/Users/Rachana/Angular1/demo1/node_modules/@ang ...

What sets apart a class from a service in NativeScript?

I am embarking on the journey of learning Nativescript + Angular2, and while reading through the tutorial, I came across this interesting snippet: We’ll build this functionality as an Angular service, which is Angular’s mechanism for reusable classes ...

Fastify fails to register middleware when using the decorate method

In the process of crafting middleware for scrutinizing the JWT transmitted during route invocations, I meticulously adhered to the guidelines stipulated in the JWT middleware manual and ported the code to TypeScript from vanilla JS. Regrettably, an anomaly ...

React component encounters 'Object may be undefined' error from TypeScript upon importing object

Recently, I started using TypeScript but encountered 'Object is possibly undefined' errors when working with imported objects and trying to iterate over their arrays. I gave the non-null assertion operator a try, but it didn't solve the iss ...

Dealing with HTTP Errors in Angular

Is there a way to notify the user if the POST, GET, or PUT method was executed correctly? Here is an example of the POST method in a component for sending data: SendData() { this.srv.PostData(this.user).subscribe( data => { console.l ...

Unfilled circle - singular point stroke in line graph for ChartJS

Is there a way to achieve this specific point style in a line chart created with ChartJS? https://i.sstatic.net/F8x85.png ...

How to Solve CORS Policy Issue When Hosting Angular Site on AWS S3?

I'm trying to host a static Angular site on AWS S3, but I'm facing a CORS policy issue. Whenever I attempt to access the index.html file after running 'ng build', I receive the following error: Access to script at '.../dist/testapp ...

The JQuery signature does not include the necessary string context

We are in the process of transitioning legacy JavaScript code to TypeScript. In our current codebase, we have jQuery selectors that utilize a string as a context: $("example", "someId"). However, when converting this to TypeScript, the definition file JQu ...

The error message "Property 'toBeInTheDocument' is not recognized by type 'JestMatchers<HTMLElement>'" is encountered when using Webpack 5 and Jest

I've been struggling to configure Jest typings with Webpack 5 and TypeScript. Even after trying various solutions, the issue persists only with "screen" and "toBeInTheDocument" in my test example below. My suspicion is that it's related to an ESL ...

Testing Angular - using observables that return varying values

I'm currently faced with the challenge of testing a component that subscribes to an observable in a service during its ngOnInit lifecycle hook. The component's behavior is expected to change based on the value received from the observable. To sim ...

My Angular-based todo application has encountered an error notification from the system

Every time I try to post something, the system responds with a 405 error message in the console. I'm not sure what caused this issue or how to resolve it. Alternatively, if I click the done button, the console displays a 500 error message. Here is t ...

Mastering the art of utilizing Angular Material's custom-palette colors for maximum impact. Unle

I have implemented a custom material-color palette where I defined the primary and accent palettes with specific shades as shown below: $my-app-primary: mat-palette($md-lightprimary ,500,900,A700 ); $my-app-accent: mat-palette($md-lightaccent, 500,900 ...

Complete encapsulation in Angular is essential when developing a custom Angular widget for hosting

I am working on an angular widget that needs to be embedded in multiple sites, but I do not have information about these sites. Unfortunately, using an IFrame is not an option for embedding the widget. Therefore, it is crucial that the widget remains com ...

Verifying Angular (2+?) Compatibility: Opening and Closing Material mat-menu on Hover [GUIDE]

After extensive research, I tried various methods to hover a material menu to display its options. However, the solutions I came across were either too complicated or ineffective. Therefore, I decided to develop my own solution by combining elements of e ...

Updating the styles of React Native components using stylesheets

I've created a unique React component with the following structure: import { StyleSheet } from 'react-native'; import { Input, Item } from 'native-base'; import Icon from 'react-native-vector-icons/FontAwesome'; import { ...