Ionic 使用离子密钥罩的Cordova实现

gkn4icbw  于 2023-03-06  发布在  Ionic
关注(0)|答案(1)|浏览(165)

我想在keycloak的帮助下进行sso认证,以便进行验证,但在下面的代码中出现此错误。我还想实现深层链接,以便获得令牌,该令牌至关重要。我如何在此代码中实现浏览器选项卡和深层链接,以便获得令牌
这下面是我的应用程序.模块.ts

/* eslint-disable prefer-const */
import { ApplicationRef, DoBootstrap, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule } from '@angular/common/http';
import { KeycloakService } from 'keycloak-angular';
import { CommonKeycloakService } from './services/keycloak/common-keycloak-service.service';
import { environment } from 'src/environments/environment';
import { InAppBrowser} from '@ionic-native/in-app-browser/ngx';
const keycloakService = new KeycloakService();
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule],
  providers: [CommonKeycloakService,
    {
      provide: KeycloakService,
      useValue: keycloakService
    }, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },InAppBrowser]
  // bootstrap: [AppComponent],
})
export class AppModule implements DoBootstrap {
  constructor() { }

  ngDoBootstrap(appRef: ApplicationRef) {
    let configKeyClock: any = {
      url: environment.keycloak.url,
      realm: environment.keycloak.realm,
      clientId: environment.keycloak.clientId,
    };
    keycloakService
      .init({
        config: configKeyClock,
        initOptions: {
          onLoad: 'check-sso',
          checkLoginIframe: false,
        },
        enableBearerInterceptor: true,
      })
      .then(() => {
        console.log('[ngDoBootstrap] bootstrap app');
        appRef.bootstrap(AppComponent);
      })
      .catch((error: any) =>
        console.error('[ngDoBootstrap] init Keycloak failed', error)
      );
  }
}

下面是应用程序组件.ts

/* eslint-disable max-len */
/* eslint-disable @typescript-eslint/dot-notation */
/* eslint-disable prefer-const */
import { Component } from '@angular/core';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { PrimaryService } from './primary.service';
import { CommonKeycloakService } from './services/keycloak/common-keycloak-service.service';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})
export class AppComponent {

  constructor(private user: PrimaryService, private commonKeycloakService: CommonKeycloakService,
    public keycloak: CommonKeycloakService,private iab: InAppBrowser) {

  }

  async ngOnInit() {
    await this.getAuthInfo();
    if (sessionStorage.getItem('userDetails') == null) {
      this.login();
    }
  };

  login() {
    if (sessionStorage.getItem('userDeatails') == null) {
      let IDP = 'samlNew';
      this.keycloak.login(IDP);
      const browser = this.iab.create('https://dbcluster.890enterprise.business/auth/realms/890Enterprise/protocol/openid-connect/auth', '_blank', 'location=yes');
    }
  }

  async getAuthInfo() {
    if (this.commonKeycloakService.isUserLoggedIn()) {
      this.commonKeycloakService.keycloakAngular
        .loadUserProfile()
        .then(async (profiles) => {
          sessionStorage.setItem('userDetails', JSON.stringify(profiles));
          // await this._httpService.generateJwt(profiles);
          let userInfo = sessionStorage.getItem('userDetails');
          let userInfo1 = JSON.parse(userInfo);
          let userName: string = userInfo1['firstName'];
          // this._httpService.userName.next(userName);
        })
        .catch((error) => {
          console.log('Error in loading profile' + JSON.stringify(error));
        });
    } else {
    }
  }
}

下面是我的键盘锁维修档案

/* eslint-disable max-len */
/* eslint-disable prefer-const */
/* eslint-disable @typescript-eslint/member-ordering */
import { Injectable } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';
import { environment } from 'src/environments/environment';
import { Observable } from 'rxjs';
import { InAppBrowser as brand} from '@ionic-native/in-app-browser/ngx';

@Injectable({
  providedIn: 'root'
})
export class CommonKeycloakService {
  activityStart: any;
  constructor(public keycloakAngular: KeycloakService,public iab: brand) {
    // this.redirectUri = environment.keycloak.url + '/realms/'
    //  + environment.keycloak.realm + '/protocol/openid-connect/logout?redirect_uri=' +
    //   environment.baseUrl + '/index.html';

    this.redirectUri = environment.keycloakRedirectBaseURl + '/index.html';
    this.activityStart = Math.floor(Date.now() / 1000);

  }


  redirectUri: any;
  idpHint: string = environment.defaultTenant;
  tenantInfo: any;
  userInfo: any;
  loginId: any;
  private _tenantcontroller = `${environment.tenantUrl}`;

  isUserLoggedIn(): boolean {
    // return true;
    if (this.keycloakAngular.isLoggedIn()) {
      try {
        const userDetails = this.keycloakAngular.getUsername();
        return true;
      } catch (e) {
        return false;
      }

    } else {
      return false;
    }

  }

  public getRedirectURI(): string {
    return this.redirectUri;
  }

  public logout() {
    this.signoutApi();
  }

  private tInf() {
    let t: any = sessionStorage.getItem('tenantInfo');
    return t;
  }

  private uInf() {
    let u: any = sessionStorage.getItem('userDetails');
    return u;
  }

  public signoutApi() {
    this.keycloakAngular.logout(this.redirectUri);
    this.keycloakAngular.logout(environment.keycloakRedirectBaseURl + '/#/auth');
  }


  public login(id: any) {
    this.idpHint = id;
    this.keycloakAngular.login({ idpHint: this.idpHint });
  }

  public setTenantInfo(info: any) {

    sessionStorage.setItem('tenantInfo', JSON.stringify(info));
  }
  public getTenantInfo() {
    return JSON.parse(this.tInf());
  }
  public setLoginId(loginId: any) {
    sessionStorage.setItem('loginId', loginId);
  }

  public getLoginId() {
    let lgnID: any = sessionStorage.getItem('loginId');
    return JSON.parse(lgnID);
  }
  public setTenantProfileInfo(info: any) {
    sessionStorage.setItem('tenantProfileInfo', JSON.stringify(info));
  }
  public getuserDetails() {
    return JSON.parse(this.uInf());
  }

  public getUserDetailsObservable(): Observable<any> {
    const userDetail = new Observable(observer => {
      setTimeout(() => {
        observer.next(JSON.parse(this.uInf()));
      }, 2500);
    });
    return userDetail;
  }

  public getTenantProfileInfo1(): Observable<any> {
    let tPInfo: any = sessionStorage.getItem('tenantProfileInfo');
    const tenantProfileInfo = new Observable(observer => {
      setTimeout(() => {
        observer.next(JSON.parse(tPInfo));
      }, 1500);
    });
    return tenantProfileInfo;
  }

  public getTenantProfileInfo() {
    let tPInfo: any = sessionStorage.getItem('tenantProfileInfo');
    return JSON.parse(tPInfo);
  }
  public clearTenantInfo() {
    sessionStorage.removeItem('tenantInfo');
  }
  public getUserDetails() {
    if (this.isUserLoggedIn()) {
      return JSON.stringify(this.keycloakAngular.loadUserProfile());
    } else {
      return '';
    }
  }

  public getToken() {
    return this.keycloakAngular.getToken();
  }

}

这也是我得到emulator image的模拟器上的错误

bwitn5fc

bwitn5fc1#

如果您尝试连接到模拟器上的localhost,您将尝试连接到在该模拟器中运行的localhost。对于大多数连接到计算机localhost的Android模拟器,您需要将“localhost”替换为“10.0.2.2“,它将转发到计算机localhost。

相关问题