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:/ ...
随机推荐
- ionic+vue+capacitor系列笔记--01项目初始化
Ionic 是什么? Ionic 是一款接近原生的 Html5 移动 App 开发框架,只需要你会 HTML.CSS 和 JavaScript 就可以开发移动 App应用,使用最基础的 Web 技术创 ...
- post方法易错地方
<body> <h1>登录</h1> <input type="text" placeholder="请输入用户名" ...
- 上古神兵,先天至宝,Win11平台安装和配置NeoVim0.8.2编辑器搭建Python3开发环境(2023最新攻略)
毫无疑问,我们生活在编辑器的最好年代,Vim是仅在Vi之下的神级编辑器,而脱胎于Vim的NeoVim则是这个时代最好的编辑器,没有之一.异步支持.更好的内存管理.更快的渲染速度.更多的编辑命令,是大神 ...
- Function接口-默认方法:andThen
Function接口 java.util.function.Function<T,R〉接口用来根据一个类型的数据得到另一个类型的数据,前者称为前置条件,后者称为后置条件. 抽象方法:apply ...
- 前端基础知识-js(一)个人学习记录
待补充: https://www.ruanyifeng.com/blog/javascript/ 运行验证: https://www.jsrun.net/new 以下仅为个人理解,如有误请指正,非常感 ...
- 软工综合实践课设——员工招聘系统(参考BOSS直聘);Pyhton实现
应用背景: 随着科学技术的发展,岗位数量越来越多,特别是每逢毕业季找工作的人数也很多,如果人们找工作或者企业招人靠纯手工的话,费时费力,仅仅是筛选简历和费劲,并且员工找工作投简历可能得需要克服时间和空 ...
- Django框架之drf:9、接口文档,coreapi的使用,JWT原理、介绍、快速使用、定制、认证
目录 Django框架之drf 一.接口文档 二.CoreAPI文档生成器 1.使用方法 三.JWT 1.JWT原理及介绍 2.JWP快速使用 3.定制返回格式 4.JTW的认证类 Django框架之 ...
- Gateway服务网关 (入门到使用)
Gateway服务网关 Gateway也要作为微服务注册到nacos中 Zuul也是网关但比较老是一种阻塞式编程:Spring Cloud Gateway 是 Spring Cloud 的一个全新项目 ...
- Rust Rand生成随机数
# in project file cargo add rand extern crate rand; use rand::Rng; fn main() { let mut rng = rand::t ...
- Vue34 VueX
1 简介 Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. vue官方搭配,专属使用 ...