Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
Şunlar için geçerlidir:
İş gücü kiracıları
Dış kiracılar (daha fazla bilgi edinin)
Bu öğretici, bir Angular tek sayfalı uygulama (SPA) oluşturmayı, kimlik doğrulaması eklemeyi ve Microsoft kimlik platformunu kullanarak kullanıcı verilerini ayıklamayı gösteren serinin ilk bölümüdür.
Bu eğitimde, siz:
- Yeni bir Angular projesi oluşturma
- Uygulama ayarlarını yapılandırma
- Uygulamaya kimlik doğrulama kodu ekleme
Önkoşullar
- Çalışma amaçlı kiracı. Varsayılan Dizininizi kullanabilir veya yeni bir kiracı ayarlayabilirsiniz.
-
Microsoft Entra yönetim merkezine, yalnızca bu kuruluş dizinindeki Hesaplar için yapılandırılmış yeni bir uygulama kaydedin. Daha fazla bilgi için Bir uygulamayı kaydetme bölümüne bakın. Daha sonra kullanmak üzere uygulamaya Genel Bakış sayfasından aşağıdaki değerleri kaydedin:
- Uygulama (istemci) kimliği
- Dizin (kullanıcı) kimliği
-
Tek sayfalı uygulama platformu yapılandırmasını kullanarak aşağıdaki yeniden yönlendirme URI'lerini ekleyin. Diğer ayrıntılar için bkz. Uygulamanıza yeniden yönlendirme URI'sini ekleme .
-
Yönlendirme URI:
http://localhost:4200/.
-
Yönlendirme URI:
- Açısal CLI
- Node.js 18.19 veya üzeri.
- Visual Studio Code veya başka bir kod düzenleyicisi.
Yeni bir Angular projesi oluşturma
Bu bölümde, Visual Studio Code'da Angular CLI kullanarak yeni bir Angular projesi oluşturacaksınız. Kiracı türünüz temelinde uygun sekmeyi seçin.
Angular projesini sıfırdan oluşturmak için şu adımları izleyin:
Yeni bir Angular projesi oluşturmak için bir terminal penceresi açın ve aşağıdaki komutu çalıştırın:
ng new msal-angular-tutorial --routing=true --style=css --strict=falseKomut,
msal-angular-tutorialadlı, yönlendirme etkin, stil için CSS kullanılan ve katı modu devre dışı bırakılmış yeni bir Angular projesi oluşturur.Proje dizinine geçin:
cd msal-angular-tutorialUygulama bağımlılıklarını yükleme:
npm install @azure/msal-browser @azure/msal-angular bootstrapKomutu
npm install @azure/msal-browser @azure/msal-angular bootstrapAzure MSAL tarayıcısını, Azure MSAL Angular'ı ve Bootstrap paketlerini yükler.Bootstrap'ın CSS yolunu açın
angular.jsonve diziyestylesekleyin:"styles": [ "src/styles.css", "node_modules/bootstrap/dist/css/bootstrap.min.css" ],Kod, Bootstrap CSS'yi dosyadaki stiller dizisine
angular.jsonekler.Giriş ve Profil bileşenleri oluşturma:
ng generate component home ng generate component profileKomutlar, Angular projesinde Giriş ve Profil bileşenlerini oluşturur.
Gereksiz dosyaları ve kodu projeden kaldırın:
rm src/app/app.component.css rm src/app/app.component.spec.ts rm src/app/home/home.component.css rm src/app/home/home.component.spec.ts rm src/app/profile/profile.component.css rm src/app/profile/profile.component.spec.tsKomutlar, gereksiz dosyaları ve kodu projeden kaldırır.
app.routes.ts'yi Visual Studio Code kullanarakapp-routing.module.tsolarak yeniden adlandırın veapp.routes.ts'nin uygulama genelindeki tüm başvurularını güncelleyin.app.config.ts'yi Visual Studio Code kullanarakapp.module.tsolarak yeniden adlandırın ve uygulama genelindeapp.config.tsile ilgili tüm başvuruları güncelleyin.
Bu adımları tamamladıktan sonra proje yapısı şöyle görünmelidir:
.
├── README.md
├── angular.json
├── package-lock.json
├── package.json
├── src
│ ├── app
│ │ ├── app-routing.module.ts
│ │ ├── app.component.html
│ │ ├── app.component.ts
│ │ ├── app.module.ts
│ │ ├── home
│ │ │ ├── home.component.html
│ │ │ └── home.component.ts
│ │ └── profile
│ │ ├── profile.component.html
│ │ └── profile.component.ts
│ ├── index.html
│ ├── main.ts
│ ├── polyfills.ts
│ └── styles.css
├── tsconfig.app.json
└── tsconfig.json
Uygulama ayarlarını yapılandırma
Bu bölümde, kimlik doğrulaması için uygulama ayarlarını yapılandıracaksınız. Uygulamayı kimlik doğrulaması için yapılandırmak üzere uygulama kaydı sırasında kaydedilen değerleri kullanacağız. Kiracı türünüz temelinde uygun sekmeyi seçin.
Uygulamayı kimlik doğrulaması için yapılandırmak üzere uygulama kaydı sırasında kaydedilen değerleri kullanacağız. Şu adımları izleyin:
src/app/app.module.tsDosyasını açın ve içeriğini aşağıdaki kodla değiştirin:// Required for Angular multi-browser support import { BrowserModule } from '@angular/platform-browser'; // Required for Angular import { NgModule } from '@angular/core'; // Required modules and components for this application import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ProfileComponent } from './profile/profile.component'; import { HomeComponent } from './home/home.component'; // HTTP modules required by MSAL import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; // Required for MSAL import { IPublicClientApplication, PublicClientApplication, InteractionType, BrowserCacheLocation, LogLevel } from '@azure/msal-browser'; import { MsalGuard, MsalInterceptor, MsalBroadcastService, MsalInterceptorConfiguration, MsalModule, MsalService, MSAL_GUARD_CONFIG, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG, MsalGuardConfiguration, MsalRedirectComponent } from '@azure/msal-angular'; const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1; export function MSALInstanceFactory(): IPublicClientApplication { return new PublicClientApplication({ auth: { // 'Application (client) ID' of app registration in the Microsoft Entra admin center - this value is a GUID clientId: "Enter_the_Application_Id_Here", // Full directory URL, in the form of https://login.microsoftonline.com/<tenant> authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here", // Must be the same redirectUri as what was provided in your app registration. redirectUri: "http://localhost:4200", }, cache: { cacheLocation: BrowserCacheLocation.LocalStorage, storeAuthStateInCookie: isIE } }); } // MSAL Interceptor is required to request access tokens in order to access the protected resource (Graph) export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration { const protectedResourceMap = new Map<string, Array<string>>(); protectedResourceMap.set('https://graph.microsoft.com/v1.0/me', ['user.read']); return { interactionType: InteractionType.Redirect, protectedResourceMap }; } // MSAL Guard is required to protect routes and require authentication before accessing protected routes export function MSALGuardConfigFactory(): MsalGuardConfiguration { return { interactionType: InteractionType.Redirect, authRequest: { scopes: ['user.read'] } }; } // Create an NgModule that contains the routes and MSAL configurations @NgModule({ declarations: [ AppComponent, HomeComponent, ProfileComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, MsalModule ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true }, { provide: MSAL_INSTANCE, useFactory: MSALInstanceFactory }, { provide: MSAL_GUARD_CONFIG, useFactory: MSALGuardConfigFactory }, { provide: MSAL_INTERCEPTOR_CONFIG, useFactory: MSALInterceptorConfigFactory }, MsalService, MsalGuard, MsalBroadcastService ], bootstrap: [AppComponent, MsalRedirectComponent] }) export class AppModule { }Kod, kullanıcı kimlik doğrulaması ve API koruması için MSAL'yi ayarlar.
MsalInterceptorveMsalGuardile API isteklerinin güvenliğini sağlamak ve yolları korumak için uygulamayı yapılandırır, kimlik doğrulama için temel bileşenleri ve hizmetleri tanımlar. Aşağıdaki değerleri Microsoft Entra yönetim merkezindeki değerlerle değiştirin.- Uygulama kaydındaki
Enter_the_Application_Id_HereileApplication (client) IDöğesini değiştirin. - Uygulama kaydındaki
Enter_the_Tenant_Info_HereileDirectory (tenant) IDöğesini değiştirin.
- Uygulama kaydındaki
Dosyayı kaydedin.
Uygulamaya kimlik doğrulama kodu ekleme
Bu bölümde, kullanıcı kimlik doğrulamasını ve oturum yönetimini işlemek için uygulamaya kimlik doğrulama kodu ekleyeceksiniz. Kiracı türünüz temelinde uygun sekmeyi seçin.
dosyasını açın
src/app/app.component.tsve içeriğini aşağıdaki kodla değiştirin:// Required for Angular import { Component, OnInit, Inject, OnDestroy } from '@angular/core'; // Required for MSAL import { MsalService, MsalBroadcastService, MSAL_GUARD_CONFIG, MsalGuardConfiguration } from '@azure/msal-angular'; import { EventMessage, EventType, InteractionStatus, RedirectRequest } from '@azure/msal-browser'; // Required for RJXS import { Subject } from 'rxjs'; import { filter, takeUntil } from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent implements OnInit, OnDestroy { title = 'Angular - MSAL Example'; loginDisplay = false; tokenExpiration: string = ''; private readonly _destroying$ = new Subject<void>(); constructor( @Inject(MSAL_GUARD_CONFIG) private msalGuardConfig: MsalGuardConfiguration, private authService: MsalService, private msalBroadcastService: MsalBroadcastService ) { } // On initialization of the page, display the page elements based on the user state ngOnInit(): void { this.msalBroadcastService.inProgress$ .pipe( filter((status: InteractionStatus) => status === InteractionStatus.None), takeUntil(this._destroying$) ) .subscribe(() => { this.setLoginDisplay(); }); // Used for storing and displaying token expiration this.msalBroadcastService.msalSubject$.pipe(filter((msg: EventMessage) => msg.eventType === EventType.ACQUIRE_TOKEN_SUCCESS)).subscribe(msg => { this.tokenExpiration= (msg.payload as any).expiresOn; localStorage.setItem('tokenExpiration', this.tokenExpiration); }); } // If the user is logged in, present the user with a "logged in" experience setLoginDisplay() { this.loginDisplay = this.authService.instance.getAllAccounts().length > 0; } // Log the user in and redirect them if MSAL provides a redirect URI otherwise go to the default URI login() { if (this.msalGuardConfig.authRequest) { this.authService.loginRedirect({ ...this.msalGuardConfig.authRequest } as RedirectRequest); } else { this.authService.loginRedirect(); } } // Log the user out logout() { this.authService.logoutRedirect(); } ngOnDestroy(): void { this._destroying$.next(undefined); this._destroying$.complete(); } }Kod, kullanıcı kimlik doğrulamasını yönetmek için MSAL'yi Angular ile tümleştirir. Oturum açma durumu değişikliklerini dinler, oturum açma durumunu görüntüler, belirteç alma olaylarını işler ve Microsoft Entra yapılandırmasına göre kullanıcıların oturumunu açmak veya kapatmak için yöntemler sağlar.
Dosyayı kaydedin.