Не удается настроить amazon-cognito-auth-js для приложения angular 4 с провайдером SAML Identity - PullRequest
0 голосов
/ 10 января 2019

Я пытаюсь интегрировать сервис-провайдера SAML с плагином AWS Cognito. Я просмотрел много документов и попытался реализовать. Однако, когда я нажимаю на кнопку входа, перенаправление не происходит. [Сценарий должен перенаправить на страницу входа Microsoft ] Поставщики Cognito и поставщики удостоверений настроены правильно. Проблема возникает, когда мне нужно пройти проверку подлинности в приложении переднего плана Может ли кто-нибудь помочь мне исправить то же самое? вот мой код

шаг 1:

npm install amazon-cognito-auth-js --save

шаг 2: добавить строку ниже в angularcli.json

"../node_modules/amazon-cognito-auth-js/dist/amazon-cognito-auth.js",
"../node_modules/amazon-cognito-auth-js/dist/amazon-cognito-auth.min.js.map",
"../node_modules/amazon-cognito-auth-js/dist/aws-cognito-sdk.js"

step3: app.component.ts

import {CognitoAuth} from 'amazon-cognito-auth-js';

шаг 4:

authData = {
    ClientId : '2*********************u',
    AppWebDomain : 'https://myApplication***********.com',
    TokenScopesArray : ['email'], 
    RedirectUriSignIn : 'https//google.com',
    RedirectUriSignOut : 'https//google.com',
    IdentityProvider : 'SAML', // e.g. 'Facebook',
    UserPoolId : 'ap-south-1_****' // Your user pool id here
};

шаг 5: в app.html

<button (click)="login()">click</button>

шаг 6:

login() {
   var auth = new CognitoAuth(this.authData);
   console.log("hello");
   auth.userhandler = {
    onSuccess: function(result) {
        alert("Sign in success");       
    },
    onFailure: function(err) {
        alert("Error!");
    }
};

моя проблема возникает, когда я нажимаю на кнопку входа, страница не перенаправляет. Пожалуйста, помогите мне

Ответы [ 3 ]

0 голосов
/ 24 января 2019

Вы можете попробовать таким образом ... рабочий код для меня.

app.component.ts

import { Component, OnInit } from '@angular/core';
import { CognitoAuth } from 'amazon-cognito-auth-js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  auth: any;
  constructor() {
    //
  }

  ngOnInit() {
    this.auth = this.initCognitoSDK();
    const curUrl = window.location.href;
    this.auth.parseCognitoWebResponse(curUrl);
  }

  initCognitoSDK() {
    const authData = {
      ClientId: 'xyz',
      AppWebDomain: 'xyz', 
      TokenScopesArray: ['openid'],
      RedirectUriSignIn: 'xyz',
      UserPoolId: 'xyz',
      RedirectUriSignOut: 'xyz',
      IdentityProvider: 'xyz',
      AdvancedSecurityDataCollectionFlag: false
    };

    const auth = new CognitoAuth(authData);

    auth.userhandler = {
      onSuccess: (result) => {
        alert('Sign in success');
        this.showSignedIn(result);
      },
      onFailure: (err) => {
        alert('Sign in failed');
      }
    };
    auth.useCodeGrantFlow();
    return auth;
  }

  login() {
    this.auth.getSession();
  }

  showSignedIn(session) {
    console.log('Session: ', session);
  }
}

app.component.html

<button (click)="login()">Login</button>
0 голосов
/ 30 января 2019

Проверьте значения AppWebDomain, TokenScopesArray и IdentityProvider authData (см. Мои комментарии ниже):

authData = {
    ClientId : '2*********************u',
    AppWebDomain : 'https://myApplication***********.com', // this should be from Cognito Console -> Your user pool -> App Integration -> Domain Name
    TokenScopesArray : ['email'], // this should be from Cognito Console -> Your user pool -> App Integration -> App Client Settings -> Allowed OAuth Scopes  
    RedirectUriSignIn : 'https//google.com',
    RedirectUriSignOut : 'https//google.com',
    IdentityProvider : 'SAML', // e.g. 'Facebook', // this should be from Cognito Console -> Your user pool -> Federation -> Identity Providers -> SAML -> Provider Name
    UserPoolId : 'ap-south-1_****' // Your user pool id here
};

Проверьте GitHub для получения дополнительной информации. Из AUTHORIZATION документации по конечной точке обратите внимание, что identity_provider может быть либо:

  • Для входа в социальную сеть допустимыми значениями являются Facebook, Google и LoginWithAmazon.
  • Для пулов пользователей Amazon Cognito это значение равно COGNITO.
  • Для других провайдеров идентификации это имя, которое вы назначили IdP в вашем пуле пользователей.

Решение

Приведенное ниже решение предназначено для входа в Google на Angular 7.

> npm install -g @angular/cli
> ng new auth-app
Angular Routing: Yes
> cd auth-app
> ng g c login
> ng g c home
> ng g s cognito
> npm install --save amazon-cognito-auth-js

В auth-app / src / app / cognito.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CognitoAuth } from 'amazon-cognito-auth-js';

@Injectable(
  {
  providedIn: 'root'
  }
)
export class CognitoService {

  authData: any;
  auth: any;
  session: any;

  constructor(private router : Router) {
    this.getAuthInstance();
  }

  getAuthInstance() {
    this.authData = {
      ClientId: '...',
      AppWebDomain: '...', 
      TokenScopesArray: ['openid', 'email', 'profile'],
      RedirectUriSignIn: 'https://localhost:4200/home',
      UserPoolId: '...',
      RedirectUriSignOut: 'https://localhost:4200',
      AdvancedSecurityDataCollectionFlag: false
    }

    this.auth = new CognitoAuth(this.authData);

    this.auth.userhandler = {
      onSuccess: session => {
        console.log('Signin success');
        this.signedIn(session);
      },
      onFailure: error => {
        console.log('Error: ' + error);
        this.onFailureMethod();
      }
    }

    //alert(this.router.url);
    //this.auth.useCodeGrantFlow();
    this.auth.parseCognitoWebResponse(this.router.url);
  }

  signedIn(session) {
    this.session = session;
  }

  onFailureMethod() {
    this.session = undefined;
  }

  get accessToken() {
    return this.session && this.session.getAccessToken().getJwtToken();
  }

  get isAuthenticated() {
    return this.auth.isUserSignedIn();
  }

  login() {
    this.auth.getSession();
    this.auth.parseCognitoWebResponse(this.router.url);
  }

  signOut() {
    this.auth.signOut();
  }
}

В auth-app / src / app / app.component.html

<router-outlet></router-outlet>

In auth-app / src / app / login / login.component.ts

import { Component, OnInit } from '@angular/core';
import { CognitoService } from '../cognito.service';
import { Router } from '@angular/router'

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

  constructor(private cognitoService : CognitoService, private router : Router) {
    if(!this.cognitoService.isAuthenticated) {
      console.log("Not authenticated")
    } else {
      console.log("Already authenticated")
      this.router.navigateByUrl(this.router.url + "/home");
    }
   }

  ngOnInit() { }

  loginWithGoogle() {
    this.cognitoService.login();
  }
}

В auth-app / src / app / login / login.component.html

<h1>Login</h1>

<button (click)="loginWithGoogle()">Login with Google</button>

В auth-app / src / app / home / home.component.ts

import { Component, OnInit } from '@angular/core';
import { CognitoService } from '../cognito.service';
import { Router } from '@angular/router';

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

  constructor(private cognitoService : CognitoService, private router : Router) {
    if(this.router.url.indexOf('?') !== -1) {
      this.router.navigateByUrl(this.router.url.substring(0, this.router.url.indexOf('?')));
    } else {
      this.cognitoService.login();
    }
  }

  ngOnInit() { }

  printToken() {
    alert(this.cognitoService.accessToken);
  }

  signOut() {
    this.cognitoService.signOut();
  }
}

В auth-app / src / app / home / home.component.html

<button (click)="printToken()">Print Token</button>

<button (click)="signOut()">Signout</button>

В auth-app / src / app / app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  { path:'', component: LoginComponent },
  { path:'home', component: HomeComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Чтобы запустить приложение с HTTPS (поскольку URL обратного вызова должен быть HTTPS для Cognito):

> npm install browser-sync --save-dev
> ng serve --ssl true --ssl-key /node_modules/browser-sync/lib/server/certs/server.key --ssl-cert /node_modules/browser-sync/lib/server/certs/server.crt

Обратите внимание, что вы должны настроить следующий URL-адрес для обратного вызова и выхода из Cognito. Перейдите в консоль Cognito -> Ваш пул пользователей -> Интеграция приложений -> Настройки клиента приложения

Перейти к https://localhost:4200

Ссылки:

0 голосов
/ 11 января 2019

Попробуйте это

установить типы, чтобы они могли иметь смысл для amazon-sdk

npm i @ types / amazon-cognito-auth-js --save-dev

затем измените ваш метод входа на этот

login() {
   const auth = new CognitoAuth(this.authData);
   console.log("hello");
   auth.userhandler.onSuccess = (result) => {
        alert("Sign in success");       
   };
   auth.userhandler.onFailure = (err) => {
        alert("Error!");
   };
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...