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:/ ...
随机推荐
- ClickHouse(12)ClickHouse合并树MergeTree家族表引擎之AggregatingMergeTree详细解析
目录 建表语法 查询和插入数据 数据处理逻辑 ClickHouse相关资料分享 AggregatingMergeTree引擎继承自 MergeTree,并改变了数据片段的合并逻辑.ClickHouse ...
- 命令行部署repmgr管理集群+switchover+切换测试
本次部署未使用securecmd/kbha工具.无需普通用户到root用户的互信. 建立系统数据库安装用户组及用户,在所有的节点执行 root用户登陆服务器,创建用户组及用户并且设置密码 [root@ ...
- Linux 常用命令(测试于CentOS8版本)
一.文件及文件夹操作 mkdir test #创建文件夹 默认在Home/test touch test.js #创建文件 默认Home/test.js touch test/test.js #创建文 ...
- 详谈pytest中的xfail
详谈pytest中的xfail 原文链接: https://docs.pytest.org/en/7.2.x/how-to/skipping.html 链接中详细阐述了skip和xfail两种情况 x ...
- Github认证
1.前言 Github关闭了密码认证,现在还有两种认证方式 token ssh 本人一直都在使用idea的可视化界面,进行git的操作,第一次使用bash进行初始化时遇到了身份验证的问题.现在简单总结 ...
- 安装kali2021.1系统
基本安装 下载地址:Downloads | Kali Linux 去官网下载,会得到kali2021.1的镜像和哈希值 打开VMware软件,新建虚拟机........................ ...
- 进程间通信 —— 管道(Interprocess Communications —— Pipes)
进程间通信 -- 管道(Interprocess Communications -- Pipes) 管道分为匿名管道(anonymous pipes)和命名管道(named pipes.)两类, 其中 ...
- 关于 Knex update 语句报错:Undefined binding(s) detected when compiling UPDATE
下图是详细的报错截图,我敢保证前端传递的数据一个不漏,但还是报我没有绑定对应的字段: 官方文档的使用案例基本上都是where 子句在 update 语句之前.但,select 语句的 where 子句 ...
- 三天吃透Java并发八股文!
本文已经收录到Github仓库,该仓库包含计算机基础.Java基础.多线程.JVM.数据库.Redis.Spring.Mybatis.SpringMVC.SpringBoot.分布式.微服务.设计模式 ...
- LeetCode算法训练-回溯 491.递增子序列 46.全排列 47.全排列 II
欢迎关注个人公众号:爱喝可可牛奶 LeetCode算法训练-回溯 491.递增子序列 46.全排列 47.全排列 II LeetCode 491. 递增子序列 分析 找出并返回所有数组中不同的递增子序 ...