Setting up Oauth2 OIDC in an Angular 8 application

I've been attempting to set up OAuth2 in my Angular project for user login. I followed the documentation, but whenever I try to log in, it keeps showing an Unauthorized error and I'm not sure how to resolve it. Here are my configurations:

auth config

export const authConfig: AuthConfig = {

// Identity Provider URL
issuer: 'my api base URL',

// Redirect URL after login
redirectUri:  window.location.origin + '/worklists',

clientId: 'oAuth2-login',
responseType: 'code',
scope: 'open worklists genstate',

};

app component

 private configure() {
 this.oauthService.configure(authConfig);
 this.oauthService.tokenValidationHandler = new JwksValidationHandler();
 this.oauthService.loadDiscoveryDocumentAndTryLogin();
 }

app module

OAuthModule.forRoot({
  resourceServer: {
    allowedUrls: ['my api base url'],
    sendAccessToken: true
  }
})

jwt interceptor

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.idToken = this.authService.getAccessToken() || '';
const authReq = req.clone({
  headers: this.idToken
    ? req.headers
      .set('Authorization', `Bearer ${this.idToken}`)
      .set('Access-Control-Allow-Origin', '*')
    : req.headers,
  params: req.params
});
console.log(authReq, 'auth req');
return next.handle(authReq);
}

this is my login service

     public login(payload: LoginPayload, rememberMe: boolean = false) {
return this.httpService.post('/oauth/authorize', payload).pipe(
  first(),
  map((resp: LoginResponse) => {
    console.log(resp, 'response')
    return this.sessionService.storeLoginResponse(resp, rememberMe);
     })
   );
 }

It seems like there might be an issue with the access token or my configuration. Any help would be greatly appreciated. Thank you.

Answer №1

While I may not be an expert in Angular, my knowledge of SPA security is quite strong. For those looking to bolster their security measures, I highly recommend utilizing the oidc-client library.

It's crucial that the token issuer remains separate from your API - consider setting up a distinct 'login' URL for this purpose.

If you're seeking guidance on navigating these concepts and ensuring a clear separation of concerns, you may find my posts helpful:

Answer №2

Kindly, review the following checklist:

  • Have you activated CORS on the server side?
  • Is your client's oAuth2-login properly registered on the server side?
  • Has the redirectUrl (including the specific port) been correctly registered on the server side?

Lastly, please attempt to enter your redirectUrl using the complete syntax (excluding window.location.origin) and then test your application once more.

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

Maintaining a consistent distance from the baseline while adjusting the font size dynamically in an HTML text element

Looking to lock a text element to the baseline while also resizing its font dynamically when the window is resized. I created a demonstration on jsfiddle. However, the issue arises when the window size changes; the distance from the bottom of the window i ...

Activating text wrapping functionality

My current project involves converting HTML to PDF using jsPDF. In order to ensure that every word appears in the exact location as it does in the original HTML, I decided to wrap each word in <span> tags. Specifically, I have a font tag (not added b ...

AngularJS - Creating a dynamic wizard experience using UI-Router

I have set up my routes using ui-router in the following way: $stateProvider .state('root', { url: "", templateUrl: 'path/login.html', controller: 'LoginController' }) .state('basket&a ...

React Functional Component fails to update on state changes

I'm in the process of creating a React application where I can input my height and weight to calculate my BMI. The goal is to display the BMI value on a diagram. To keep things organized, I decided to break down the functionality into smaller componen ...

Unable to send image file and string via XHR is causing issues

This task may seem straightforward, but I've been struggling with it for hours. My goal is to upload an image file along with stringified coordinates to crop the image on the server-side. Below is my client-side code: var formdata = new FormD ...

Tips for center-aligning layouts in Angular Material

I am struggling with the Angular Material flex layout, so I took this directly from the Angular Material website. Based on the documentation for layout container, items are arranged in a row with a max-height of 100% and max-width matching the width of th ...

Compilation of various route parameters

This route configuration example showcases how to extract parameters from a URL: URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby Route: /Chapter/:chapterId/Section/:sectionId Using this setup, we can obtain the following object: {chapt ...

When attempting to view the PDF file, it appears completely void

After spending countless hours on this task, I'm still not making any progress. My goal is to download a PDF file from my server while currently running the operation on localhost. However, whenever I open the downloaded PDF, all I see is a blank whit ...

Searching for Node.js tutorials using Google API on YouTube

I'm attempting to utilize the Google APIs in Node for a YouTube search. Currently, I'm following a tutorial found here: https://github.com/google/google-api-nodejs-client/#google-apis-nodejs-client I've managed to get some basic functiona ...

Using jQuery's .live('click') method will only bind to the initial element found on the webpage

I developed a custom jQuery plugin that attaches to 8 different elements on a webpage. Within each element, I intended to utilize the .live() method to bind a click event to a link, triggering a form submission via ajax. However, I encountered an issue whe ...

Observe the classList object of the material element to obtain its properties

I am currently using the mat-autocomplete feature and I am trying to remove focus from the input after selecting an element without needing a click. The mat-focused class within the mat-form-field is responsible for focusing on the mat-auto-complete. By re ...

Transferring a zipped JSZip file to a Java server

I am striving to achieve the task of uploading a zip file to my Angular 2 front-end, transferring it to my Java (Spring Boot) back-end, and extracting the xml files enclosed within the zip. Currently, I am utilizing JSZip for handling the zip file uploads ...

Updating the state of Formik

Currently, I'm knee-deep in a React project that requires a slew of calculations. To manage my forms, I've turned to Formik, and for extra utility functions, I've enlisted the help of lodash. Here's a peek at a snippet of my code: impor ...

Guide to dynamically loading a component using a variable name in Vue.js?

Is it possible to dynamically load a component in a vue.js application using a variable name? For example, if I have the following component registered: <template id="goal"> <h1>Goal:{{data.text}}</h1> </template> Instead of di ...

Creating a jQuery AJAX call with a vanilla JavaScript promise

I recently transitioned my website to a Single Page Application (SPA), which involves working with only one HTML page populated using JavaScript. In order to simplify the process, I decided to consolidate my JavaScript files into one. However, while creati ...

Error: ChunkLoadError - Unable to load chunk for node_modules_next_dist_client_dev_noop_js

As I was working through the basics tutorial on the Next.js website, I encountered an issue when reaching the Global Styles step. The runtime error that started appearing is as follows: ChunkLoadError: Loading chunk node_modules_next_dist_client_dev_noop_j ...

Loading V-Select with Data from JSON Using Vue.js

I tried to populate my v-select multiselect element using a JSON object, but unfortunately it did not work as expected. Here is the result I encountered: https://i.sstatic.net/kd1Gl.png <v-select v-model="serviceValues" :items="serviceO ...

Exploring Angular 7's Child Routes

Currently, I am facing an issue with cleanly separating Routes based on Forms and Menus. For instance, I have a Menu Item named Setup which contains sub Items called Bucket and Tags. Both Bucket and Tags are utilized throughout the application to categoriz ...

Differences in outcomes have been observed between the elementLocated and findElements functions

Currently, I am in the process of developing Webdriver automation for a specific web application. As part of this process, I have created a test that seems to be functioning well most of the time but occasionally encounters an issue. it('verifies pre ...

What is the process for developing an interface adapter using TypeScript?

I need to update the client JSON with my own JSON data Client JSON: interface Cols { displayName: string; } { cols:[ { displayName: 'abc'; } ] } My JSON: interface Cols { label: string; } { cols:[ { label:&a ...