错误 DOMException:无法在 'Document' 上执行 'querySelector'

ERROR DOMException: Failed to execute 'querySelector' on 'Document'

我正在尝试使用 Angular 6 应用程序设置 Adal。我遵循这些说明:

错误 DOMException:无法在 'Document' 上执行 'querySelector':'#id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1....

在我的重定向页面中,Azure AD 回调似乎有效:

 ngOnInit() {
   console.log("AuthRedirect: calling handle window");
   this.adal.handleWindowCallback();
   console.log("AuthRedirect: calling handle window ended");
   console.log(this.adal.userInfo.token);
   console.log(this.adal.userInfo.authenticated);
 }

我不确定这是 ADAL 异常还是路由器对回调中处理的参数不满意。欢迎所有建议。

--------------------回答------------------ 我不记得我是如何解决这个问题的,但这是一个可行的解决方案。

身份验证拦截器:

import { Injectable } from '@angular/core';
import { HttpEvent,HttpHandler,HttpRequest,HttpInterceptor } from '@angular/common/http';
import { AdalService } from 'adal-angular4';
import { Observable } from 'rxjs';


@Injectable()
export class AuthenticationInterceptor implements HttpInterceptor {
    constructor(private adalService: AdalService) { }

    intercept(req: HttpRequest<any>, next:HttpHandler): Observable<HttpEvent<any>>{
        const authHeader = this.adalService.userInfo.token;
        var header = 'Bearer ' + authHeader;
        const authReq = req.clone({headers: req.headers.set('Authorization', header)});
        return next.handle(authReq);
    }

}

AuthenticationGuard:

import { Injectable } from '@angular/core';
import { Router, CanActivate,  ActivatedRoute, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import { AdalService } from 'adal-angular4';

@Injectable()
export class AuthenticationGuard implements CanActivate {
  constructor(private adal: AdalService, private route: ActivatedRoute) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    if (this.adal.userInfo.authenticated) {
      return true;
    }

    console.log("Adal Login");
    var url = state.url;
    console.log(url);
    sessionStorage.setItem("adal.return.url",url);
    this.adal.login();

    return false;
  }
}

app.module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { HttpClientModule,HTTP_INTERCEPTORS } from '@angular/common/http';
import { PerfectScrollbarModule } from 'ngx-perfect-scrollbar';
import { PERFECT_SCROLLBAR_CONFIG } from 'ngx-perfect-scrollbar';
import { PerfectScrollbarConfigInterface } from 'ngx-perfect-scrollbar';
import { AuthenticationGuard } from './authentication-guard';
import { AuthenticationInterceptor } from './authentication-interceptor';

const DEFAULT_PERFECT_SCROLLBAR_CONFIG: PerfectScrollbarConfigInterface = {
  suppressScrollX: true
};

import { AppComponent } from './app.component';

// Import containers
import { DefaultLayoutComponent } from './containers';

import { P404Component } from './views/error/404.component';
import { P500Component } from './views/error/500.component';
import { LoginComponent } from './views/login/login.component';
import { RegisterComponent } from './views/register/register.component';

import { AdalService } from 'adal-angular4';
import { ModalModule } from 'ngx-bootstrap/modal';

const APP_CONTAINERS = [
  DefaultLayoutComponent
];

import {
  AppAsideModule,
  AppBreadcrumbModule,
  AppHeaderModule,
  AppFooterModule,
  AppSidebarModule,
} from '@coreui/angular';

// Import routing module
import { AppRoutingModule } from './app.routing';

// Import 3rd party components
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { TabsModule } from 'ngx-bootstrap/tabs';
import { ChartsModule } from 'ng2-charts/ng2-charts';
import { TechnicalManagerReportComponent } from './technical-manager-report/technical-manager-report.component';
import { AssetReportComponent } from './asset-report/asset-report.component';
import { VesselsComponent } from './vessels/vessels.component';
import { AuthRedirectComponent } from './auth-redirect/auth-redirect.component';
import { DynamicSidebarNavComponent } from './dynamic-sidebar-nav/dynamic-sidebar-nav.component';
import { LogoutComponent } from './logout/logout.component';
import { RatingsComponent } from './ratings/ratings.component';

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule,
    AppAsideModule,
    AppBreadcrumbModule.forRoot(),
    AppFooterModule,
    AppHeaderModule,
    AppSidebarModule,
    PerfectScrollbarModule,
    BsDropdownModule.forRoot(),
    TabsModule.forRoot(),
    ChartsModule,
    HttpClientModule,
    ModalModule.forRoot() 
  ],
  declarations: [
    AppComponent,
    ...APP_CONTAINERS,
    P404Component,
    P500Component,
    LoginComponent,
    RegisterComponent,
    TechnicalManagerReportComponent,
    AssetReportComponent,
    VesselsComponent,
    AuthRedirectComponent,
    DynamicSidebarNavComponent,
    LogoutComponent,
    RatingsComponent
  ],
  providers: [
    AdalService, 
      AuthenticationGuard,
      { provide: HTTP_INTERCEPTORS, useClass: AuthenticationInterceptor, multi: true }
  //   {
  //   provide: LocationStrategy,
  //   useClass: HashLocationStrategy
  // }
],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

app.routing:

 {path:'authredirect', component: AuthRedirectComponent},  
 {path:'ratings', component: RatingsComponent,canActivate: [AuthenticationGuard]},  
 {path:'vessels',component: VesselsComponent,canActivate: [AuthenticationGuard]},

授权重定向页面:

import { Component, OnInit, NgZone } from '@angular/core';
import { AdalService } from 'adal-angular4';
import { Router,ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-auth-redirect',
  templateUrl: './auth-redirect.component.html',
  styleUrls: ['./auth-redirect.component.scss']
})
export class AuthRedirectComponent implements OnInit {

  constructor(private router: Router, private adal: AdalService, private _zone: NgZone) { }

  ngOnInit() {
    this.adal.handleWindowCallback();

    var url = sessionStorage.getItem("adal.return.url");

    console.log(url);

    setTimeout(() => {
      this._zone.run(
        () => this.router.navigate([url])
      );
    }, 500);
  }

}

app.module:

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { environment } from '../environments/environment';
import { AdalService } from 'adal-angular4';

@Component({
  // tslint:disable-next-line
  selector: 'body',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent implements OnInit {



  constructor(private router: Router, private adalService: AdalService) { }

  ngOnInit() {
    this.router.events.subscribe((evt) => {
      if (!(evt instanceof NavigationEnd)) {
        return;
      }
      window.scrollTo(0, 0);
    });

    this.adalService.init(environment.adalConfig);
  }
}

我的 Azure AD B2C 设置遇到了这个问题。如果有人遇到这个问题,请尝试将 response_mode=query 添加到您的 oauth url.

示例url 生成器函数

export function b2cLoginUrl() {
    return `https://${appConfig.directory}.b2clogin.com/${appConfig.directory}.onmicrosoft.com/oauth2/v2.0/authorize?p=${appConfig.signin_signup_userflow}&client_id=${appConfig.client_id}&nonce=${appConfig.nonce}&redirect_uri=${appConfig.redirect_uri}&scope=${appConfig.scope}&response_type=${appConfig.response_type}&prompt=${appConfig.prompt}&response_mode=${appConfig.response_mode}`
}