#angular #azure-active-directory
#angular #azure-active-directory
Вопрос:
В настоящее время я слежу за этим документом, но я немного обеспокоен, пожалуйста, помогите мне. Может кто-нибудь сказать мне, как поместить этот код javascript в соответствующий файл.
Во-первых, включите класс Interceptor в качестве поставщика для вашего приложения:
import { MsalInterceptor, MsalModule } from "@azure/msal-angular";
import { HTTP_INTERCEPTORS, HttpClientModule } from "@angular/common/http";
@NgModule({
// ...
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
}
]
}
Затем предоставьте as карту защищенных ресурсов MsalModule.forRoot()
protectedResourceMap
и включите в нее эти области consentScopes
. URL-адреса, которые вы предоставляете в protectedResourceMap
коллекции, учитывают регистр символов.
@NgModule({
// ...
imports: [
// ...
MsalModule.forRoot({
auth: {
clientId: 'Enter_the_Application_Id_here', // This is your client ID
authority: 'https://login.microsoftonline.com/Enter_the_Tenant_Info_Here', // This is your tenant info
redirectUri: 'Enter_the_Redirect_Uri_Here' // This is your redirect URI
},
cache: {
cacheLocation: 'localStorage',
storeAuthStateInCookie: isIE, // Set to true for Internet Explorer 11
},
},
{
popUp: !isIE,
consentScopes: [
'user.read',
'openid',
'profile',
],
unprotectedResources: [],
protectedResourceMap: [
['https://graph.microsoft.com/v1.0/me', ['user.read']]
],
extraQueryParameters: {}
})
],
});
Наконец, извлеките профиль пользователя с помощью HTTP-запроса:
const graphMeEndpoint = "https://graph.microsoft.com/v1.0/me";
getProfile() {
this.http.get(graphMeEndpoint).toPromise()
.then(profile => {
this.profile = profile;
});
}
Получить пользовательский токен автоматически
const requestObj = {
scopes: ["user.read"]
};
this.authService.acquireTokenSilent(requestObj).then(function (tokenResponse) {
// Callback code here
console.log(tokenResponse.accessToken);
}).catch(function (error) {
console.log(error);
});
Добавьте следующий код для выхода пользователя из системы:
logout() {
this.authService.logout();
}
Заранее спасибо!
Ответ №1:
Чтобы использовать класс перехватчика, который автоматически получает токены для исходящих запросов, использующих угловой http-клиент в MSAL Angular, необходимо внести изменения на соответствующие страницы
app.module.ts
import { MsalInterceptor, MsalModule } from "@azure/msal-angular";
import { HTTP_INTERCEPTORS, HttpClientModule } from "@angular/common/http";
@NgModule({
// ...
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
}
]
}
С тем же набором файлов Msal.Module.forRoot внутри импорта, как показано ниже
@NgModule({
// ...
imports: [
// ...
MsalModule.forRoot({
auth: {
clientId: 'Enter_the_Application_Id_here', // This is your client ID
authority: 'https://login.microsoftonline.com/Enter_the_Tenant_Info_Here', // This is your tenant info
redirectUri: 'Enter_the_Redirect_Uri_Here' // This is your redirect URI
},
cache: {
cacheLocation: 'localStorage',
storeAuthStateInCookie: isIE, // Set to true for Internet Explorer 11
},
},
{
popUp: !isIE,
consentScopes: [
'user.read',
'openid',
'profile',
],
unprotectedResources: [],
protectedResourceMap: [
['https://graph.microsoft.com/v1.0/me', ['user.read']]
],
extraQueryParameters: {}
})
],
});
Чтобы получить профиль пользователя с помощью HTTP-запроса, вы можете использовать любой компонент или компонент в компоненте, как показано ниже.
constructor(private authService: MsalService, private http: HttpClient) { }
getProfile() {
this.http.get(GRAPH_ENDPOINT)
.toPromise().then(profile => {
this.profile = profile;
});
}
Чтобы установить функцию выхода из системы в app.component.ts
logout() {
this.authService.logout();
}
Пожалуйста, обратитесь к этому документу для получения дополнительной информации, и есть пример GitHub, который может помочь вам в справочнике по реализации