我正在尝试使用Azure AD创建一个PoC应用程序集,具有Angular(其他或变体前端)的WebApi,以对我的联合身份验证用户进行身份验证。
我的后端工作正常,身份验证/ MFA正常运行,并显示登录提示。
我已经获得了Angular应用程序的Microsoft示例,但是我为该应用程序的实现而苦苦挣扎,我该使用MSAL在前端获得令牌,并让后端接受该令牌并通过联合身份验证用户?
这是我的示例中的app.module.ts
代码,其中
export const protectedResourceMap:[string, string[]][]=[ ['https://localhost:5001/',['api://--------------/access_as_user']] , ['https://graph.microsoft.com/v1.0/me', ['user.read']] ];
const isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 || window.navigator.userAgent.indexOf("Trident/") > -1;
@NgModule({
declarations: [
AppComponent, HomeComponent, ProductComponent, ErrorComponent, ProductDetailComponent, TodoListComponent, UserDataComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
RouterModule.forRoot(appRoutes,{useHash:true}) ,
MsalModule.forRoot({
clientID: '-----------',
authority: "https://login.microsoftonline.com/common/",
validateAuthority: true,
redirectUri: "http://localhost:4200/",
cacheLocation : "localStorage",
storeAuthStateInCookie: isIE, // set to true for IE 11
postLogoutRedirectUri: "http://localhost:4200/",
navigateToLoginRequestUrl: true,
popUp: !isIE,
consentScopes: [ "user.read", "openid", "profile", "api://------------/access_as_user"],
unprotectedResources: ["https://www.microsoft.com/en-us/"],
protectedResourceMap: protectedResourceMap,
logger: loggerCallback,
correlationId: '1234',
piiLoggingEnabled: true
}
),
],
providers: [ProductService, TodoListService, HttpServiceHelper,
{provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true}
],
bootstrap: [AppComponent]
})
答案 0 :(得分:1)
我使用@azure/msal-angular
-前端NPM Package和passport-azure-ad
-后端NPM Package
然后我们从前端获取令牌,并在后端验证令牌,并获取附加到该用户的电子邮件,并将其与数据库中的用户链接。但这只有在Microsoft Graph在后端验证了令牌后才会发生。
因此,在我们的登录页面上,这是我们导入的import { BroadcastService, MsalService } from '@azure/msal-angular';
在NgOnInit
中,我们有这个
ngOnInit() {
this.broadcastService.subscribe('msal:loginFailure', payload => {
this.loggedIn = false;
this.loaded = false;
});
this.broadcastService.subscribe('msal:loginSuccess', payload => {
console.log(payload);
if (payload instanceof Object) {
// Do something
}
});
}
这是我在实际的Microsoft登录按钮上拥有的代码
microsoftLogin() {
this.loaded = true;
this.msal
.loginPopup()
.then(token => {
this.microsoftAPILogin(token); // A call to send the token to our API
this.loaded = false;
this.loggedIn = true;
})
.catch(err => {
this.loggedIn = false;
this.loaded = false;
});
}