一.app.module.ts中设定应用程式

1.将MSAL Angular相关设置封装为auth.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MsalGuard, MsalBroadcastService, MsalModule, MsalService, MSAL_GUARD_CONFIG, MSAL_INSTANCE, MsalGuardConfiguration, MsalRedirectComponent } from '@azure/msal-angular';
import { IPublicClientApplication, PublicClientApplication, InteractionType } from '@azure/msal-browser';
import { LogLevel, Configuration, BrowserCacheLocation } from '@azure/msal-browser'; const isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 || window.navigator.userAgent.indexOf("Trident/") > -1; export function MSALInstanceFactory(): IPublicClientApplication {
return new PublicClientApplication( {
auth: {
clientId: '', // 应用clientId
authority: 'https://login.microsoftonline.com/common',,
redirectUri: '',
},
cache: {
cacheLocation: BrowserCacheLocation.LocalStorage, // LocalStorage缓存
storeAuthStateInCookie: isIE, // IE11或Edge上遇到问题
},
});
} export function MSALGuardConfigFactory(): MsalGuardConfiguration {
return {
interactionType: InteractionType.Redirect,
};
} @NgModule({
declarations: [],
imports: [
MsalModule,
CommonModule
],
providers: [
{
provide: MSAL_INSTANCE,
useFactory: MSALInstanceFactory
},
{
provide: MSAL_GUARD_CONFIG,
useFactory: MSALGuardConfigFactory
},
MsalService,
MsalGuard,
MsalBroadcastService,
],
})
export class AuthModule { }

2.app.module.ts引入auth.module.ts;同时引入MsalRedirectComponent 重新导向组件

import { AppComponent } from './app.component';
import { AuthModule } from './auth/auth.module';
import {MsalRedirectComponent } from '@azure/msal-angular';//导入处理重新导向的组件 @NgModule({
declarations: [
...
AppComponent,
],
imports: [
...
AuthModule,
],
bootstrap: [AppComponent,MsalRedirectComponent],
})

3.將 <app-redirect> 选取器新增至 src/index.html。 此选取器是由 MsalRedirectComponent 使用

4.登录;订阅LOGIN_SUCCESS 事件。 可从使用重新导向的成功登入存取結果

import { Component, OnInit } from '@angular/core';
import { MsalBroadcastService, MsalService } from '@azure/msal-angular';
import { AuthenticationResult, EventMessage, EventType, InteractionStatus } from '@azure/msal-browser';
import { Subject } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators'; @Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.scss']
})
export class HomePageComponent implements OnInit { private readonly _destroying$ = new Subject<void>();
username: string | undefined; constructor(
private authService: MsalService,
private msalBroadcastService: MsalBroadcastService
) { } ngOnInit(): void {
this.msalBroadcastService.msalSubject$
.pipe(
filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),
takeUntil(this._destroying$)
)
.subscribe((result: EventMessage) => {
const payload = result.payload as AuthenticationResult;
this.authService.instance.setActiveAccount(payload.account)
this.setLoginDisplay();
}); this.setLoginDisplay();
} setLoginDisplay(){
if(this.authService.instance.getAllAccounts().length > 0){
this.username = this.authService.instance.getAllAccounts()[0].name;
}
} login(){
this.authService.loginRedirect();
} logout() {
this.authService.logoutRedirect();
} }

5.根据重新导向的成功登入結果定义路由守卫

import { MsalService } from '@azure/msal-angular';
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { concatMap, catchError, map } from 'rxjs/operators';
import { Observable, of } from 'rxjs'; @Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate { constructor(
private authService: MsalService,
) { } canActivate(
route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.authService.handleRedirectObservable()
.pipe(
concatMap(() => {
if (!this.authService.instance.getAllAccounts().length) {
this.authService.loginRedirect();
return of(false);
}
return of(true);
}),
catchError(() =>{
return of(false)
} )
);
}
}

Angular单页应用程式 (SPA)+Azure AD重新导向登入的更多相关文章

  1. 单页应用(SPA,Single-page-App)和多页应用(MPA,Multi-page App)的区别

    单页应用(SPA,Single-page-App)和多页应用(MPA,Multi-page App)的区别 参考博客:https://www.jianshu.com/p/4c9c29967dd6

  2. 关于单页应用(SPA)的经验之谈

    时下SPA单页应用如火如荼,对前端乃至后端开发都带来不小的冲击和变革.笔者整理了下笔记,决定写一下以前基于iframe做单页博客的一些经验方法. 对于单页应用,笔者没有找到最官方的定义.在笔者看来,在 ...

  3. Angular单页应用&AngularJS内部实现原理

    回顾 自定义指令 登录后获取登录信息session 首先在登录验证的时候保存一个user 在学生管理页面中运用ajax调用获取到登录的用户信息 对注销按钮添加点击事件:调用ajax在表现层给user赋 ...

  4. require实现单页应用程序(SPA)

    写了一个测试代码,用require.js配合它的一个插件text.js实现了最简单的单页应用程序,简单的记录一下,方便以后复习, git地址:https://github.com/lily1010/r ...

  5. 使用 AngularJS 开发一个大规模的单页应用(SPA)

      本文的目标是基于单页面应用程序开发出拥有数百页的内容,包括认证,授权,会话状态等功能,可以支持上千个用户的企业级应用. 下载源代码 介绍 (SPA)这样一个名字里面蕴含着什么呢? 如果你是经典的S ...

  6. 单页应用 WebApp SPA 骨架 框架 路由 页面切换 转场

    这里收录三个同类产品,找到他们花了我不少时间呢. 张鑫旭写的mobilebone自述:mobile移动端,PC桌面端页面无刷新过场JS骨架,简单.专注!http://www.zhangxinxu.co ...

  7. SPA解释:单页应用程序

    单页Web应用(single page web application,SPA),就是只有一张Web页面的应用,是加载单个HTML 页面并在用户与应用程序交互时动态更新该页面的Web应用程序. 单页W ...

  8. SPA (单页应用程序)

    单页Web应用 编辑 单页Web应用(single page web application,SPA),就是只有一张Web页面的应用.单页应用程序 (SPA) 是加载单个HTML 页面并在用户与应用程 ...

  9. React构建单页应用方法与实例

    React作为目前最流行的前端框架之一,其受欢迎程度不容小觑,从这门框架上我们可以学到许多其他前端框架所缺失的东西,也是其创新性所在的地方,比如虚拟DOM.JSX等.那么接下来我们就来学习一下这门框架 ...

  10. AnjularJs的增删改查(单页网站)

    2016.6.4 学习文献: 你的第一个AngularJS应用:https://segmentfault.com/a/1190000000347412 AngularJS 提交表单的方式:http:/ ...

随机推荐

  1. MyBatis的使用七(处理表与表之间的关系)

    本文主要讲述mybatis的处理表与表之间的关系 一. 介绍t_emp和t_dept表 1. t_emp表结构 2. t_dept表结构 二. 数据表的关系 1. 阐明关系 一个部门可以有多个员工,但 ...

  2. Android IO 框架 Okio 的实现原理,到底哪里 OK?

    本文已收录到 AndroidFamily,技术和职场问题,请关注公众号 [彭旭锐] 提问. 前言 大家好,我是小彭. 今天,我们来讨论一个 Square 开源的 I/O 框架 Okio,我们最开始接触 ...

  3. JAVA虚拟机17---栈帧(局部变量表-操作数栈-动态连接-返回地址)

    借鉴:转https://blog.csdn.net/u011069294/article/details/107106755,他的虚拟机专栏:https://blog.csdn.net/u011069 ...

  4. CNCF社区首个!KubeEdge达到软件供应链SLSA L3等级

    摘要:在v1.13.0版本中,KubeEdge项目已达到 SLSAL3等级(包括二进制和容器镜像构件),成为CNCF社区首个达到SLSA L3等级的项目. 本文分享自华为云社区<CNCF社区首个 ...

  5. UBUNTU18.04安装使用ORB-SLAM2

    1.下载: git clone https://github.com/raulmur/ORB_SLAM2.git ORB_SLAM2 2.依赖项: sudo apt install autotools ...

  6. 网络继电器的EPICS IOC搭建

    http://www.corxnet.com/product/showproduct.php?id=36 https://item.taobao.com/item.htm?spm=a1z10.5-c- ...

  7. ES6中的class对象和它的家人们

    在ES6中新增了一个很重要的特性: class(类).作为一个在2015年就出了的特性, 相信很多小伙伴对class并不陌生.但是在日常开发中使用class的频率感觉并不高(可能仅限于作者),感觉对c ...

  8. WPF ScrollViewer 没有效果

    ScrollViewer组件外组件如果是StackPanel组件 需要给StackPanel 设置高度,ScrollViewer 才会有滚动条 如果不想设置StackPanel高度,可以把StackP ...

  9. PostGIS之几何有效性

    1. 概述 PostGIS 是PostgreSQL数据库一个空间数据库扩展,它添加了对地理对象的支持,允许在 SQL 中运行空间查询 PostGIS官网:About PostGIS | PostGIS ...

  10. 如何设置VBA代码的密码?如何取消VBA代码的密码?

    经常有网友问,用Access把软件开发好了,怎么样设置VBA代码的密码?以保护自己的代码不被同事修改.这里简单整理了一下.设置VBA代码的密码及取消VBA代码的密码步骤如下:1.打开任意一个窗体,进入 ...