Angular单页应用程式 (SPA)+Azure AD重新导向登入
一.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重新导向登入的更多相关文章
- 单页应用(SPA,Single-page-App)和多页应用(MPA,Multi-page App)的区别
单页应用(SPA,Single-page-App)和多页应用(MPA,Multi-page App)的区别 参考博客:https://www.jianshu.com/p/4c9c29967dd6
- 关于单页应用(SPA)的经验之谈
时下SPA单页应用如火如荼,对前端乃至后端开发都带来不小的冲击和变革.笔者整理了下笔记,决定写一下以前基于iframe做单页博客的一些经验方法. 对于单页应用,笔者没有找到最官方的定义.在笔者看来,在 ...
- Angular单页应用&AngularJS内部实现原理
回顾 自定义指令 登录后获取登录信息session 首先在登录验证的时候保存一个user 在学生管理页面中运用ajax调用获取到登录的用户信息 对注销按钮添加点击事件:调用ajax在表现层给user赋 ...
- require实现单页应用程序(SPA)
写了一个测试代码,用require.js配合它的一个插件text.js实现了最简单的单页应用程序,简单的记录一下,方便以后复习, git地址:https://github.com/lily1010/r ...
- 使用 AngularJS 开发一个大规模的单页应用(SPA)
本文的目标是基于单页面应用程序开发出拥有数百页的内容,包括认证,授权,会话状态等功能,可以支持上千个用户的企业级应用. 下载源代码 介绍 (SPA)这样一个名字里面蕴含着什么呢? 如果你是经典的S ...
- 单页应用 WebApp SPA 骨架 框架 路由 页面切换 转场
这里收录三个同类产品,找到他们花了我不少时间呢. 张鑫旭写的mobilebone自述:mobile移动端,PC桌面端页面无刷新过场JS骨架,简单.专注!http://www.zhangxinxu.co ...
- SPA解释:单页应用程序
单页Web应用(single page web application,SPA),就是只有一张Web页面的应用,是加载单个HTML 页面并在用户与应用程序交互时动态更新该页面的Web应用程序. 单页W ...
- SPA (单页应用程序)
单页Web应用 编辑 单页Web应用(single page web application,SPA),就是只有一张Web页面的应用.单页应用程序 (SPA) 是加载单个HTML 页面并在用户与应用程 ...
- React构建单页应用方法与实例
React作为目前最流行的前端框架之一,其受欢迎程度不容小觑,从这门框架上我们可以学到许多其他前端框架所缺失的东西,也是其创新性所在的地方,比如虚拟DOM.JSX等.那么接下来我们就来学习一下这门框架 ...
- AnjularJs的增删改查(单页网站)
2016.6.4 学习文献: 你的第一个AngularJS应用:https://segmentfault.com/a/1190000000347412 AngularJS 提交表单的方式:http:/ ...
随机推荐
- 【Unity 框架】 QFramework v1.0 使用指南 工具篇: 16. LiveCodingKit 写代码不用停止运行的利器 | Unity 游戏框架 | Unity 游戏开发 | Unity 独立游戏
我们在用 Unity 开发的时候,每次编写或修改一点代码就需要进行 停止运行->编写代码->等待编译->运行游戏. 而在很多情况下这个过程是一个比较耗神的过程,因为开发者需要等待,还 ...
- 为什么 Linux 需要虚拟内存(转载)
为什么 Linux 需要虚拟内存 原文链接: https://draveness.me/whys-the-design-os-virtual-memory/ 操作系统中的 CPU 和主内存(Main ...
- eigen的简单用法汇总
Eigen帮助文档的地址:http://eigen.tuxfamily.org/dox/pages.html Eigen的论坛:http://forum.kde.org/viewforum.php?f ...
- 数字列表number,目标值target,找到number中两个不同数字之和等于target的数字,输出下标并顺序排列 ----笔试题记录扩展
一.思路: 输入:数字列表number,目标值target 判断条件:数字列表中两个不同数字相加等于target 输出:符合条件的两个数字的下标,下标顺序排列 方法1: def list(number ...
- Cesium鼠标移动到模型上,给模型添加高亮轮廓(四)
2023-01-09 Cesium虽然也支持两种方式(Entity和Primitive)加载3D Tiles数据, 但因为多数情况下3D Tiles数据都是成片区的数据,数据量比较大,所以为了保证性能 ...
- Git常用指令集合🔥
关联文章:Git入门图文教程(1.5W字40图)--深入浅出.图文并茂 指令-查看状态信息 指令 描述 git --version 查看git版本 git status 查看本地仓库状态,比较常用的指 ...
- [IOI2013]robots 机器人
题目传送门 思路 简单题,设函数 \(f_i\) 表示当时间为 \(i\) 时是否能够收拾好所有玩具,则 \(f_i\) 显然是单调的. 所以我们可以考虑二分. 设我们当前二分到 \(x\),我们先把 ...
- redis服务创建失败:Could not create server TCP listening socket 127.0.0.1:6379: bind
1. redis-cli.exe 2.shutdown 如果出现 (error) NOAUTH Authentication required.,则需要验证之前设置的密码(没出现请忽略第三步) 3 ...
- Linux 一次性创建多个文件
创建多个文件,文件名数字编号是递增的,在文件名后面加上{n..m}: touch file-{1..10}.txt
- 基于C++的OpenGL 02 之着色器
1. 概述 本文基于C++语言,描述OpenGL的着色器 环境搭建以及绘制流程可参考: 基于C++的OpenGL 01 之Hello Triangle - 当时明月在曾照彩云归 - 博客园 (cnbl ...