본문 바로가기

Web Application/Angular

[Angular] Angular 라우팅 전략(2) - Url에서 # 없애는 방법

728x90
반응형
SMALL

이전 포스팅에서 Angular 라우팅 전략에 대해 설명한 적이 있었다.

라우팅 전략을 살펴 본 이유는, URL에 #이 붙어서 나와 오류가 발생했기 때문이였다.

 

2021.06.16 - [Web Application/Angular] - [Angular] Angular 라우팅 전략(1) - Url에서 #을 사용하는 이유

 

[Angular] Angular 라우팅 전략(1) - Url에서 #을 사용하는 이유

Angular에서 작업하는 도중 아래 이미지와 같이 URL에 #이 붙어서 표출됐다. #이 붙는 바람에 페이지를 처리할 때 오류가 발생하여 해결 방법이 필요하던 상황.. Angular 라우팅 전략 #이 붙은 이유는 A

lims-dev.tistory.com

 


 

오류 상황

 

Angular에서 Office Add-in을 개발할 때 MSAL을 통해 로그인 기능을 구현했을 경우,

아래와 같이 경로에 #(해시)가 붙어서 리턴이 된다.

https://localhost:44383/#id_token=

 

해당 이슈는 useHash: true 라우터에서 설정하면 발생하는 오류인데,

Microsoft 자습서에서는 HashLocationStrategy를 사용하라고 한다.

 

https://learn.microsoft.com/en-us/graph/application-saml-sso-configure-api?tabs=http%2Cpowershell-script 

 

Use Microsoft Graph APIs to configure SAML-based single sign-on - Microsoft Graph

Follow these steps to create and configure a SAML-based single sign-on (SSO) for your application in Azure AD using the Microsoft Graph API.

learn.microsoft.com

 

angluar 실행 시 #이 붙음

 

 

Angular 애플리케이션에서 해시 위치 전략 사용

해시 위치 전략을 지정하지 않으면 애플리케이션에서 경로 간 탐색이 작동하지 않을 수 있습니다. 두 가지 방법 중 하나로 이 작업을 수행할 수 있습니다. 먼저 다음 예제와 같이 앱 모듈에서 위치 전략에 대한 공급자를 지정할 수 있습니다. app.module.ts 파일로 들어갑니다.

 

import { LocationStrategy, HashLocationStrategy } from '@angular/common';
// Other imports suppressed for brevity

@NgModule({
  providers: [
    { provide: LocationStrategy, useClass: HashLocationStrategy },
    // Other providers suppressed
  ],
  // Other module properties suppressed
})
export class AppModule { }

 

또는

 

import { RouterModule, Routes } from '@angular/router';
// Other imports suppressed for brevity

const routes: Routes = // route definitions go here

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: true })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

 

출처 : https://learn.microsoft.com/en-us/office/dev/add-ins/develop/add-ins-with-angular2

 

Develop Office Add-ins with Angular - Office Add-ins

Use Angular to create an Office Add-in as a single page application.

learn.microsoft.com


 

 

해결방법

 

HashLocationStrategy와 함께 라우팅을 사용하고 있으면 CustomLocationStrategy를 만들어주면 된다고 해서,

CustomLocationStrategy를 만들어서 해결했다.

 

app.module.ts

 

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';
import { MsalModule, MsalInterceptor, MsalGuard } from '@azure/msal-angular';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { LocationStrategy, HashLocationStrategy, PathLocationStrategy } from '@angular/common';
import { APP_BASE_HREF } from '@angular/common';

import { CustomLocationStrategy } from "./services/custom-location-strategy.service";

const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1;
export var _msalConfig: Configuration = {
  auth: {
    clientId:  // This is your client ID
    authority:  // This is your tenant ID
   /redirectUri: // This is your redirect URI
  },
  cache: {
    cacheLocation: "localStorage",
    storeAuthStateInCookie: isIE,
  }
};


@NgModule({
  declarations: [

  ],
  imports: [
    RouterModule.forRoot(appRoutes, { useHash: true }),
    MsalModule.forRoot(_msalConfig, {
      popUp: !isIE,
      consentScopes: [
        'user.read',
        'openid',
        'profile',
      ],
      unprotectedResources: [],
      protectedResourceMap: [
        ['https://graph.microsoft.com/beta/me', ['user.read']]
      ],
      extraQueryParameters: {}
    })
  ],
  providers: [
    { provide: APP_BASE_HREF, useValue: window.location.pathname },
    { provide: LocationStrategy, useClass: CustomLocationStrategy },
  ],
  bootstrap: [AppComponent],
})
export class AppModule { }

 

custom-location-strategy.service.ts 파일

 

import { Injectable } from '@angular/core';
import { HashLocationStrategy } from "@angular/common";
@Injectable()
export class CustomLocationStrategy extends HashLocationStrategy {
  prepareExternalUrl(internal: string): string {
    const url = this.getBaseHref() + '#' + internal;
    return url;
  }
}

 

 

 

microsoft msal 설정 방법

 

https://learn.microsoft.com/ko-kr/azure/active-directory/develop/tutorial-v2-angular-auth-code

 

자습서: 인증 코드 흐름을 사용하여 인증할 수 있도록 Microsoft ID 플랫폼을 사용하는 Angular 앱 만

이 자습서에서는 Microsoft ID 플랫폼을 사용하여 사용자를 로그인하고 사용자를 대신해 Microsoft Graph API를 호출하도록 액세스 토큰을 가져오면서 인증 코드 흐름을 사용하는 Angular SPA(단일 페이지

learn.microsoft.com

 

 

 

 

728x90
반응형
LIST