【angular5项目积累总结】结合adal4实现http拦截器(token)
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable } from "rxjs/Observable";
import { Adal4Service } from '../adal/adal4.service';
import { Router } from '@angular/router';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
private adalService: Adal4Service,
private router: Router
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const resource = this.adalService.GetResourceForEndpoint(request.url);
let authenticatedCall: Observable<HttpEvent<any>>;
if (resource) {
if (this.adalService.userInfo.authenticated) {
authenticatedCall = this.adalService.acquireToken(resource)
.flatMap((token: string) => {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
return next.handle(request).catch(this.handleError);
});
}
else {
this.adalService.refreshDataFromCache();
authenticatedCall = Observable.throw(new Error('User Not Authenticated.'));
}
}
else { authenticatedCall = next.handle(request).catch(this.handleError); }
return authenticatedCall;
}
private handleError(err: HttpErrorResponse): Observable<any> {
if (err.status === 401 || err.status === 403) {
console.log(err.message);
this.router.navigate(['dataService'], {});
return Observable.of(err.message);
}
// handle your auth error or rethrow
return Observable.throw(err);
}
}
Adal4Interceptor
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Adal4Service } from './adal4.service';
@Injectable()
export class Adal4Interceptor implements HttpInterceptor {
constructor(public adal4Service: Adal4Service) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.adal4Service.userInfo.token}`
}
});
return next.handle(request);
}
}
adal4service
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Adal4User } from './adal4-user';
import * as adalLib from 'adal-angular';
import { adal } from 'adal-angular';
import User = adal.User;
@Injectable()
export class Adal4Service {
private adalContext: adal.AuthenticationContext;
private adal4User: Adal4User = {
authenticated: false,
username: '',
error: '',
token: '',
profile: {}
};
constructor() { }
public init(configOptions: adal.Config) {
if (!configOptions) {
throw new Error('You must set config, when calling init.');
}
const existingHash = window.location.hash;
let pathDefault = window.location.href;
if (existingHash) {
pathDefault = pathDefault.replace(existingHash, '');
}
configOptions.redirectUri = configOptions.redirectUri || pathDefault;
configOptions.postLogoutRedirectUri = configOptions.postLogoutRedirectUri || pathDefault;
this.adalContext = adalLib.inject(configOptions);
window.AuthenticationContext = this.adalContext.constructor;
this.updateDataFromCache(this.adalContext.config.loginResource);
}
public get config(): adal.Config {
return this.adalContext.config;
}
public get userInfo(): Adal4User {
return this.adal4User;
}
public login(): void {
this.adalContext.login();
}
public loginInProgress(): boolean {
return this.adalContext.loginInProgress();
}
public logOut(): void {
this.adalContext.logOut();
}
public handleWindowCallback(): void {
const hash = window.location.hash;
if (this.adalContext.isCallback(hash)) {
const requestInfo = this.adalContext.getRequestInfo(hash);
this.adalContext.saveTokenFromHash(requestInfo);
if (requestInfo.requestType === this.adalContext.REQUEST_TYPE.LOGIN) {
this.updateDataFromCache(this.adalContext.config.loginResource);
} else if (requestInfo.requestType === this.adalContext.REQUEST_TYPE.RENEW_TOKEN) {
this.adalContext.callback = window.parent.callBackMappedToRenewStates[requestInfo.stateResponse];
}
if (requestInfo.stateMatch) {
if (typeof this.adalContext.callback === 'function') {
if (requestInfo.requestType === this.adalContext.REQUEST_TYPE.RENEW_TOKEN) {
if (requestInfo.parameters['access_token']) {
this.adalContext.callback(this.adalContext._getItem(this.adalContext.CONSTANTS.STORAGE.ERROR_DESCRIPTION)
, requestInfo.parameters['access_token']);
}
else if (requestInfo.parameters['error']) {
this.adalContext.callback(this.adalContext._getItem(this.adalContext.CONSTANTS.STORAGE.ERROR_DESCRIPTION), null);
this.adalContext._renewFailed = true;
}
}
}
}
}
if (window.location.hash) {
window.location.href = window.location.href.replace(window.location.hash, '');
}
}
public getCachedToken(resource: string): string {
return this.adalContext.getCachedToken(resource);
}
public acquireToken(resource: string) {
const _this = this;
let errorMessage: string;
return Observable.bindCallback(acquireTokenInternal, function (token: string) {
if (!token && errorMessage) {
throw (errorMessage);
}
return token;
})();
function acquireTokenInternal(cb: any) {
let s: string = null;
_this.adalContext.acquireToken(resource, (error: string, tokenOut: string) => {
if (error) {
_this.adalContext.error('Error when acquiring token for resource: ' + resource, error);
errorMessage = error;
cb(<string>null);
} else {
cb(tokenOut);
s = tokenOut;
}
});
return s;
}
}
public getUser(): Observable<any> {
return Observable.bindCallback((cb: (u: adal.User) => User) => {
this.adalContext.getUser(function (error: string, user: adal.User) {
if (error) {
this.adalContext.error('Error when getting user', error);
cb(null);
} else {
cb(user);
}
});
})();
}
public clearCache(): void {
this.adalContext.clearCache();
}
public clearCacheForResource(resource: string): void {
this.adalContext.clearCacheForResource(resource);
}
public info(message: string): void {
this.adalContext.info(message);
}
public verbose(message: string): void {
this.adalContext.verbose(message);
}
public GetResourceForEndpoint(url: string): string {
return this.adalContext.getResourceForEndpoint(url);
}
public refreshDataFromCache() {
this.updateDataFromCache(this.adalContext.config.loginResource);
}
private updateDataFromCache(resource: string): void {
const token = this.adalContext.getCachedToken(resource);
this.adal4User.authenticated = token !== null && token.length > 0;
const user = this.adalContext.getCachedUser() || { userName: '', profile: undefined };
if (user) {
this.adal4User.username = user.userName;
this.adal4User.profile = user.profile;
this.adal4User.token = token;
this.adal4User.error = this.adalContext.getLoginError();
} else {
this.adal4User.username = '';
this.adal4User.profile = {};
this.adal4User.token = '';
this.adal4User.error = '';
}
};
}
Adal4User
export class Adal4User {
authenticated: boolean;
username: string;
error: string;
profile: any;
token: string;
}
adal-angular.d
declare var AuthenticationContext: adal.AuthenticationContextStatic;
declare namespace adal {
interface Config {
tenant?: string;
clientId: string;
redirectUri?: string;
instance?: string;
endpoints?: any;
popUp?: boolean;
localLoginUrl?: string;
displayCall?: (urlNavigate: string) => any;
postLogoutRedirectUri?: string;
cacheLocation?: string;
anonymousEndpoints?: string[];
expireOffsetSeconds?: number;
correlationId?: string;
loginResource?: string;
resource?: string;
extraQueryParameter?: string;
navigateToLoginRequestUrl?: boolean;
}
interface User {
userName: string;
profile: any;
}
interface RequestInfo {
valid: boolean;
parameters: any;
stateMatch: boolean;
stateResponse: string;
requestType: string;
}
interface AuthenticationContextStatic {
new (config: Config): AuthenticationContext;
}
interface AuthenticationContext {
CONSTANTS: any;
REQUEST_TYPE: {
LOGIN: string,
RENEW_TOKEN: string,
UNKNOWN: string
};
callback: any;
_getItem: any;
_renewFailed: any;
instance: string;
config: Config;
login(): void;
loginInProgress(): boolean;
getCachedToken(resource: string): string;
getCachedUser(): User;
registerCallback(expectedState: string, resource: string, callback: (message: string, token: string) => any): void;
acquireToken(resource: string, callback: (message: string, token: string) => any): void;
promptUser(urlNavigate: string): void;
clearCache(): void;
clearCacheForResource(resource: string): void;
logOut(): void;
getUser(callback: (message: string, user?: User) => any): void;
isCallback(hash: string): boolean;
getLoginError(): string;
getRequestInfo(hash: string): RequestInfo;
saveTokenFromHash(requestInfo: RequestInfo): void;
getResourceForEndpoint(endpoint: string): string;
handleWindowCallback(): void;
log(level: number, message: string, error: any): void;
error(message: string, error: any): void;
warn(message: string): void;
info(message: string): void;
verbose(message: string): void;
}
}
interface Window {
AuthenticationContext: any;
callBackMappedToRenewStates: any;
}
logged-in.guard
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Adal4Service } from './adal4.service';
@Injectable()
export class LoggedInGuard implements CanActivate{
constructor(private adalService: Adal4Service,
) {
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean {
this.adalService.handleWindowCallback();
if (this.adalService.userInfo.authenticated) {
return true;
} else {
this.adalService.login();
return false;
}
}
}
【angular5项目积累总结】结合adal4实现http拦截器(token)的更多相关文章
- 【angular5项目积累总结】遇到的一些问题以及解决办法
1.项目中字符串特别是\r\n,替换成br之后,在页面换行无法生效? 答:绑定元素 innerHTML. <div class="panel-body" [innerHTML ...
- 【angular5项目积累总结】avatar组件
View Code import { Component, HostListener, ElementRef } from '@angular/core'; import { Adal4Service ...
- 【angular5项目积累总结】优秀组件以及应用实例
1.手机端 图片预览组件 组件:sideshow 效果图:(预览图全屏 且可以左右移动) code: <div class="row ui-app-s ...
- 【angular5项目积累总结】消息订阅服务
code import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; @Injectable ...
- 【angular5项目积累总结】侧栏菜单 navmenu
View Code import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/co ...
- 【angular5项目积累总结】breadcrumb面包屑组件
view code <div class="fxs-breadcrumb-wrapper" aria-label="Navigation history" ...
- 【angular5项目积累总结】文件上传
<div class="form-group row"> <label class="col-sm-2 col-form-label"> ...
- 【angular5项目积累总结】文件下载
download() { const token = localStorage.getItem('token'); let headers: HttpHeaders = new HttpHeaders ...
- 【angular5项目积累总结】自定义管道 OrderBy
import { Injectable, Pipe } from '@angular/core'; @Pipe({ name: 'orderBy' }) @Injectable() export cl ...
随机推荐
- C#: 以管理员权限运行包含有cd命令的.bat文件
最近在做项目的时候遇到一种情:用C#程序以管理员权限去执行一个bat文件,且此bat文件里面有cd命令来进入文件的下一级目录,比如: echo test begin cd test1 setup1.e ...
- 100道Java基础面试题
1.什么是B/S架构?什么是C/S架构 B/S(Browser/Server),浏览器/服务器程序 C/S(Client/Server),客户端/服务端,桌面应用程序 2.你所知道网络协议有那些? H ...
- XGBoost,GBDT原理详解,与lightgbm比较
xgb原理: https://www.jianshu.com/p/7467e616f227 https://blog.csdn.net/a819825294/article/details/51206 ...
- Python 读取文件中unicode编码转成中文显示问题
Python读取文件中的字符串已经是unicode编码,如:\u53eb\u6211,需要转换成中文时有两种方式 1.使用eval: eval("u"+"\'" ...
- Swift5 语言指南(二十四) 泛型
通用代码使您能够根据您定义的要求编写可以使用任何类型的灵活,可重用的函数和类型.您可以编写避免重复的代码,并以清晰,抽象的方式表达其意图. 泛型是Swift最强大的功能之一,Swift标准库的大部分内 ...
- python学习笔记12-深浅拷贝
以上为浅拷贝. .copy()函数 赋值:数据完全共享(=赋值是在内存中指向同一个对象,如果是可变(mutable)类型,比如列表,修改其中一个,另一个必定改变 如果是不可变类型(immutable) ...
- OS之内存管理 --- 虚拟内存管理(二)
关于虚拟内存管理之前的请看:OS之内存管理 - 虚拟内存管理(一) 帧分配 每个进程对的最小帧数是由操作系统的体系结构决定的,但是最大帧数是由可用物理内存的数量决定的.所以在这之间,对于进程的帧的分配 ...
- IntelliJ IDEA中Debug的使用技巧
当运行结果跟我们设想的不一致时,我们就可以用debug进行代码调试,下面是我在日常开发中对debug的一些小结 (一)基本介绍 本篇文章是基于IntelliJ IDEA2018.3.2版本,Debug ...
- Feign status 400 reading 问题分析
背景:项目使用的是微服务架构,采用springboot来开发,所有的服务都是基于内嵌tomcat来运行 问题:项目部署到测试环境之后,偶尔在后台日志会看到这样的日志:Feign status 400 ...
- python垃圾回收
python垃圾回收 python垃圾回收主要使用引用计数来跟踪和回收垃圾.在引用计数的基础上,通过“标记—清除”解决容器对象可能产生的循环引用问题,通过“分代回收”以空间换时间的方法提高垃圾回收效率 ...