简体   繁体   English

错误 DOMException:无法在“文档”上执行“querySelector”

[英]ERROR DOMException: Failed to execute 'querySelector' on 'Document'

I am trying to setup Adal with an Angular 6 application.我正在尝试使用 Angular 6 应用程序设置 Adal。 I follow these instructions:我遵循以下说明:

ERROR DOMException: Failed to execute 'querySelector' on 'Document': '#id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1....错误 DOMException:无法在“文档”上执行“querySelector”:“#id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1....

In my redirect page that is being called back by Azure AD seems to work:在我被 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);
 }

I am not sure whether this is an ADAL exception or it is the router not being happy with the parameters handled in the callback.我不确定这是 ADAL 异常还是路由器对回调中处理的参数不满意。 All suggestions are welcome.欢迎提出所有建议。

--------------------- answer ------------------- I don't remember exactly how I solved the problem but here is a working solution. --------------------- 回答 ------------------- 我不记得我是如何解决的问题,但这是一个有效的解决方案。

authentication incepter:身份验证接收器:

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]},

auth redirect page:身份验证重定向页面:

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);
  }
}

Was having this problem with my Azure AD B2C setup.我的 Azure AD B2C 设置遇到了这个问题。 If anyone runs into this issue, try adding response_mode=query to your oauth url.如果有人遇到此问题,请尝试将response_mode=query添加到您的 oauth url。

Example url builder function示例 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}`
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 6 - ERROR DOMException:无法在&#39;Element&#39;上执行&#39;setAttribute&#39;: - Angular 6 - ERROR DOMException: Failed to execute 'setAttribute' on 'Element': 错误 DOMException:无法在“XMLHttpRequest”上执行“打开”:无效的 URL - ERROR DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL 错误 DOMException:无法在“元素”上执行“setAttribute”:“{{”不是有效的属性名称 - ERROR DOMException: Failed to execute 'setAttribute' on 'Element': '{{' is not a valid attribute name Angular 元素:DOMException:无法在“CustomElementRegistry”上执行“define” - Angular Element: DOMException: Failed to execute 'define' on 'CustomElementRegistry' 未捕获的 DOMException:无法在“WorkerGlobalScope”上执行“importScripts” - Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope' 未捕获的DOMException:无法在'Window'上执行'postMessage' - Uncaught DOMException: Failed to execute 'postMessage' on 'Window' 错误:“document.querySelector(...)为null” - ERROR: “document.querySelector(…) is null” 错误 DOMException:无法在“元素”上执行“setAttribute”:“novalidate(ngSubmit)”不是有效的属性名称 - ERROR DOMException: Failed to execute 'setAttribute' on 'Element': 'novalidate(ngSubmit)' is not a valid attribute name DOMException:无法在“IDBObjectStore”上执行“getAll”:事务在 angular 中不活动 - DOMException: Failed to execute 'getAll' on 'IDBObjectStore': The transaction is not active in angular DOMException:无法在“元素”上执行“setAttribute”:“[routerLink”不是有效的属性名称 - DOMException: Failed to execute 'setAttribute' on 'Element': '[routerLink' is not a valid attribute name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM