Angular에서 Azure Active Directory 인증 수행

16922 단어 AzureAngularAzureAD
Angular에서 Azure Active Directory(=AAD) 인증을 수행하는 방법에 대해 알아봅니다.

전제



adal-angular4: Angular 4/5/6/7 ADAL Wrapper이 설치되어 있음
angular4 라는 이름입니다만, Angular8까지 대응하고 있습니다.

environments.ts


export const environment = {
  tenant: '{AADのテナントId}',
  clientId: '{認証用AADアプリケーションのアプリケーションId}'
};

app.component.ts


import { Component, OnInit } from '@angular/core';
import { AdalService } from 'adal-angular4';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  constructor(private adalService: AdalService) {
    adalService.init(
      {
        tenant: environment.tenant,
        clientId: environment.clientId,
        redirectUri: window.location.origin + '/',
      }
    );
  }

  ngOnInit() {
    this.adalService.handleWindowCallback();
  }

}


app-router.module.ts



라우팅 모듈에서 액세스를 제어합니다.

인증할 경로에 canActivate: [LoggedInGuard]를 지정합니다.

그렇게 하면 아래의 예에서는 HomeComponent 를 읽어들이기 전에 LoggedInGuard 를 실행하고 반환값이 True이면 읽습니다.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from '../home/home.component';
import { CounterComponent } from '../counter/counter.component';
import { FetchDataComponent } from '../fetch-data/fetch-data.component';
import { LoginComponent } from '../page/login/login.component';
import { LoggedInGuard } from '../service/logged-in.guard';

const routes: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full', canActivate: [LoggedInGuard]},
  { path: 'login', component: LoginComponent },
  { path: 'counter', component: CounterComponent },
  { path: 'fetch-data', component: FetchDataComponent },
];

@NgModule({
  declarations: [],
  imports: [
    RouterModule.forRoot(routes)
  ],
  exports: [
    RouterModule
  ]
})
export class AppRouterModule { }


loggedIn.guard.ts



Guard를 만듭니다.
this.adalService.userInfo.authenticated가 true가 아니면 로그인 화면 (/login)으로 이동합니다.
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AdalService } from 'adal-angular4';

@Injectable({
  providedIn: 'root'
})
export class LoggedInGuard implements CanActivate {
  constructor(
    private adalService: AdalService,
    private router: Router
    ) { }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      if (this.adalService.userInfo.authenticated) {
        return true;
      }
      sessionStorage.setItem('redirect_url', window.location.href);
      this.router.navigate(['/login']);
      return false;
  }

}


login.component.ts


import { Component, OnInit } from '@angular/core';
import { AdalService } from 'adal-angular4';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  constructor(
    private adalService: AdalService,
    private router: Router,
  ) { }

  ngOnInit() {
    if (this.adalService.userInfo.authenticated) {
      this.router.navigate(['/']);
    } else {
      this.adalService.login(); // このメソッドが呼ばれると、MSの認証画面に
    }
  }

}


이제 http://localhost:4200에 액세스하면 MS 인증 화면이 표시됩니다.


적절한 계정으로 로그인하면 브라우저의 세션 저장소에 adal.idtoken으로 jwt가 저장됩니다.

좋은 웹페이지 즐겨찾기