Navigating with Angular 2: Redirecting Azure AD login URI

I am currently exploring Azure AD integration for logging into an Angular 2 application. The Github link provided below demonstrates a simple method to log in without the use of any authentication libraries.

Sign in via Microsoft Graph using Typescript and Angular 2

Although the setup works effectively, I encountered an issue where the redirection after login always returns to the main screen where the login process started. I am attempting to redirect to a different localhost view but have been unsuccessful so far.

While I was able to successfully redirect to https://www.google.com, I faced challenges when trying to customize the redirect URL within the code snippet found at /src/authHelper/authHelper.ts:

    login() {
    //redirect to get id_token
    window.location.href = "https://login.microsoftonline.com/" + SvcConsts.TENTANT_ID + 
        "/oauth2/authorize?response_type=id_token&client_id=" + SvcConsts.CLIENT_ID + 
        "&redirect_uri=" + encodeURIComponent('HTTPS://WWW.GOOGLE.COM') + 
        "&state=SomeState&nonce=SomeNonce";
}

Additionally, ensure that the Reply URL is correctly configured in your Azure Active Directory to facilitate successful redirection. This setting can be adjusted by selecting your Azure AD, then navigating to the application under that AD, and configuring the Reply URL on the Configure tab within the old Azure portal.

--HOWEVER--

I have encountered difficulties replicating this behavior with a custom localhost view. Every attempt to replace https://www.google.com with URLs like https://localhost:8080/redirect resulted in browser errors such as "ERR_CONNECTION_CLOSED."

The current Reply URL for my web app in Azure AD is set as:

https://i.sstatic.net/DtLAk.png

Here's my updated login code utilizing local references (this):

    login() {
    console.log("Logging in!");

    //redirect to get id_token
    window.location.href = "https://login.microsoftonline.com/" + this.TENTANT_ID + 
        "/oauth2/authorize?response_type=id_token&client_id=" + this.CLIENT_ID + 
        "&redirect_uri=" + encodeURIComponent('https://localhost:8080/#/redirect') + 
        "&state=SomeState&nonce=SomeNonce";
}

Furthermore, I have configured router/routes in my app.component.ts file:

import { Component, ChangeDetectionStrategy } from '@angular/core';
import { Routes, ROUTER_DIRECTIVES } from '@angular/router';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { AuthenticationComponent } from '../authentication/authentication.component';
import { AuthRedirectComponent } from '../authRedirect/authRedirect.component';
import { HomeComponent } from '../home/home.component';

import '../style/styles.less';

@Component({
   selector: 'app',
   template:
   `
    <h1>{{title}}</h1>
    <em>some content</em>
    <app-login></app-login>
    <router-outlet></router-outlet>
   `,
   directives: [ROUTER_DIRECTIVES, AuthenticationComponent],
   changeDetection: ChangeDetectionStrategy.OnPush
})

@Routes([
    { path: '/', component: HomeComponent },
    { path: '/redirect', component: AuthRedirectComponent }
])

export class AppComponent {
    title: string = "App Component Title";

} 

Has anyone encountered similar issues or found a workaround? As I require Azure AD for authentication and prefer localhost views due to deployment constraints, alternatives like Auth0 are not viable options at this stage.

Thank you

Answer №1

To set the redirect URL, you need to specify it as http://localhost:8080.

login() {
    // Redirect to get id_token
    window.location.href = "https://login.microsoftonline.com/" + SvcConsts.TENTANT_ID + 
        "/oauth2/authorize?response_type=id_token&client_id=" + SvcConsts.CLIENT_ID + 
        "&redirect_uri=" + encodeURIComponent('http://localhost:8080') + 
        "&state=YOUR_ROUTE&nonce=SomeNonce&response_mode=query";
}

In the state value, specify your specific route so that when authentication is successful, it redirects like http://localhost:8080/?state=YOUR_ROUTE&id_token=YOUR_TOKEN. After a successful redirection, retrieve data from the URL in your main app.component.ts file like

import {Router, ActivatedRoute, Params} from '@angular/router';

constructor(private activatedRoute: ActivatedRoute) {}

    ngOnInit() {
        this.activatedRoute.queryParams.subscribe((params: Params) => {

                let token = params['id_token'];
        // save token 
                if(typeof token !="undefined"){
                window.localStorage.setItem('authToken',token);
                  let route = JSON.parse(params['state']);
                 window.location.href =route;
                }
            });
    }

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 require assistance in displaying a dynamic, multi-level nested object in HTML using AngularJS

I have a complex dynamic object and I need to extract all keys in a nested ul li format using AngularJS. The object looks like this: [{"key":"campaign_1","values":[{"key":"Furniture","values":[{"key":"Gene Hale","values":[{}],"rowLevel":2},{"key":"Ruben A ...

Unselect all options in Angular's multiple selection feature

Objective: My goal is to ensure that when I invoke the myMethod() function, all options are unselected. Current Issue: Currently, calling myMethod() will only deselect the last option, leaving the others selected if they were previously selected. Possibl ...

Typescript encountering onClick function error during the build process

My current challenge involves creating a submit function for a button in my application. However, when I attempt to build the project, I encounter a typing error that is perplexing me. Despite trying various methods, I am unable to decipher how to resolve ...

What is the proper way to access the global `angular` variable in Angular and TypeScript when using AngularJS?

I'm currently integrating an Angular 4 component into a large monolithic AngularJS application. The challenge I face lies in the restrictions of the AngularJS project's build system, which limits me to only modifying the project's index.html ...

The error at events.js:154 was not properly handled and caused an 'error' event to be thrown

Encountered an error while creating an Angular 2 application. I followed the instructions from this link to create a sample application. Upon running npm start Received the following error, events.js:154 throw er; // Unhandled 'error' even ...

React Native is throwing an error message saying that the Component cannot be used as a JSX component. It mentions that the Type '{}' is not assignable to type 'ReactNode'

Recently, I initiated a new project and encountered errors while working with various packages such as React Native Reanimated and React Navigation Stack. Below is my package.json configuration: { "name": "foodmatch", "version ...

ngSwitchCase provider not found

While following a tutorial and trying to implement what I learned, I encountered an error that I'm having trouble understanding. The browser console shows an error message stating [ERROR ->]<span *ngSwitchCase="true">, but I can't figure ...

My reselect function seems to be malfunctioning - I'm not receiving any output. Can anyone help me

I'm looking to implement reselect in my code to retrieve the shopping cart based on product ids. Here's my reselect.ts file: import { createSelector } from "reselect"; import { RootState } from "../store"; export const shopp ...

The most efficient method for distributing code between TypeScript, nodejs, and JavaScript

I am looking to create a mono repository that includes the following elements: shared: a collection of TypeScript classes that are universally applicable WebClient: a react web application in JavaScript (which requires utilizing code from the shared folde ...

Rendering options for Ngx typeahead in Angular 6

Currently, I am utilizing the Angular ngx-bootstrap typeahead plugin available at this link https://i.sstatic.net/wcrmT.png While using the input typeahead in a modal, The option values appear inside the modal container. However, I do not want them to ...

Developing a loader feature in React

I've been working on incorporating a loader that displays when the component has not yet received data from an API. Here's my code: import React, {Component} from 'react' import './news-cards-pool.css' import NewsService fro ...

Discovering the interface type of class properties in order to implement a factory method

I am struggling with implementing a factory method in my code. I want to be able to pass not only a Class type to instantiate but also a set of default values for the properties within the class. My goal is to have the compiler notify me if I try to pass i ...

In Angular 5 and Node Express, a fresh session is initialized for every individual request made

I'm currently working on a project using Angular 5 to connect to my NodeJS server. After the user logs in, I store their information in the req.session object. However, when I attempt to make another request from the Angular 5 app to access the API, ...

Angular CRUD Form Data Conversion Update

After selecting the date 3/2/2021 in my Angular create CRUD form, it gets passed to MongoDB as 2021-03-02T00:00:00.000+00:00 and then displayed on the update CRUD form as 2021-03-02T00:00:00.000Z. How can I convert this to 'M/d/yyyy' format? (I ...

Expanding interfaces dynamically in Typescript

Currently, I am facing a challenge while attempting to integrate an existing React Native module equipped with the following props: useComponent1: boolean useComponent2: boolean This is how the implementation looks like: render(){ if(useComponent1){ ...

Guide to removing selected value from a combobox in Angular

I am working on a simple HTML file that consists of one combobox and one clear button. I want the clear button to remove the selected value from the combobox when clicked. Below is my code: mat-card-content fxLayout="row wrap" fxLayoutAlign="left" fxLayou ...

How to show specific images by clicking on particular items in Ionic 3 on a separate page

Can someone assist me with displaying specific images from a slider gallery? I am struggling to figure out how to show only the January edition when clicking on it in eighteen.html, while hiding the February and March editions. It has been 2 days of unsucc ...

An issue has occurred while attempting to differentiate '[object Object]'. Please note that only arrays and iterable objects are permitted

myComponent.component.ts ngOnInit() { this.getData.getAllData().subscribe( response => { console.log(response); this.dataArray = response; }, () => console.log('there was an error') ); } myservi ...

Router failure resulted in an internal server error

When navigating to a page in my router, I make a REST API request to retrieve data from the server in the beforeEnter clause as shown below: beforeEnter: (to, form, next) => { getData().then( (response) => { ...

Is it possible for two distinct TypeScript interfaces to share identical keys while allowing for varying values?

Is it possible in TypeScript to ensure that objValidator has the same keys as the obj it validates, with different key values? Any suggestions on how I can achieve this requirement? Specifically, the obj and objValidator should share identical keys. I wan ...